Magic Call Methods in Java

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.

+6
source share
2 answers

You absolutely can through reflection using your functions, such as

 public Method getMethod(String name, Class<?>... parameterTypes) 

which can be used to determine if a class has specific methods, but I don’t see how your problem cannot be solved with the right use of interfaces, inheritance and method overrides.

Functions such as reflection are designed to manage certain otherwise insoluble problems, but Java is not PHP, so you should try to avoid using it whenever possible, as this is not in the philosophy of the language.

+5
source

Isn't that a whole point of inheritance and redefinition?

Base class:

 public Object foo() { return this.myMap.get(defaultKey).method(); } 

Subclass:

 @Overrides public Object foo() { return whateverIWant; } 
+2
source

Source: https://habr.com/ru/post/908831/


All Articles