Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magically call methods in Java

Is there some way of using magic methods in Java like there is 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'm using Project Lombok annotations for getter and setter methods to simplify the code.

Let's consider that that my map contains several items mapped by String and the defaultKey defines the default one.

What I would like is to be able to call foo.getName() which would return the default name as foo.myMap.get(defaultKey).getName().

The reason I can't just write all the getters manually is that the Foo class is in fact inherited with generics and the the inner class might be different.

I sort of need something like:

   function Object __call(method) {
           if (exist_method(this.method)
                return this.method();
           else 
                return this.myMap.get(defaultKey).method();
   }

Is this somehow possible in Java?

EDIT:

I made a more precise example of what I am trying to achieve here: https://gist.github.com/1864457

The only reason of doing this is to "shorthand" the methods in the inner class.

like image 732
Vojtěch Avatar asked Feb 19 '12 14:02

Vojtěch


2 Answers

You absolutely can through reflection by using its features like

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

that can be used to see if a class has some methods defined but I don't see how your problem couldn't be solved with a proper use of interfaces, inheritance and overriding of methods

Features like reflection are provided to manage certain, otherwise unsolvable, issues but Java is not PHP so you should try to avoid using it when possible, since it's not in the philosophy of the language.

like image 125
Jack Avatar answered Sep 30 '22 13:09

Jack


Isn't it the whole point of inheritance and overriding?

Base class:

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

Subclass:

@Overrides
public Object foo() {
    return whateverIWant;
}
like image 22
JB Nizet Avatar answered Sep 30 '22 12:09

JB Nizet