Is there a way to use magic methods in Java, like in PHP with __call
?
For instance:
class foo { @Setter @Getter int id; @Getter Map <String, ClassInFoo> myMap; protected class ClassInFoo { @Setter @Getter String name; } @Setter String defaultKey; }
I use Project Lombok annotations for the getter and setter methods to simplify the code.
Let's consider that my map contains several elements displayed by String, and defaultKey defines the default value.
What I would like is to call foo.getName()
, which will return the default name as foo.myMap.get(defaultKey).getName()
.
The reason I cannot just write all getters manually is because the Foo class is actually inherited by the generics, and the inner class may be different.
I need something like:
function Object __call(method) { if (exist_method(this.method) return this.method(); else return this.myMap.get(defaultKey).method(); }
How is this possible in Java?
EDIT:
I made a more accurate example of what I'm trying to achieve here: https://gist.github.com/1864457
The only reason for this is to “shorthand” the methods in the inner class.
source share