user12026681
user12026681

Reputation:

get java.lang.reflect.Method safely

Similar interfaces are used for an event system as "listeners"

interface Updatable {
  void update();
}

Events (→ all "listen" methods) are called by

spot(Method, Object... event);

To achieve. Get java.lang.reflect.Method of "listeners" like update in Updatable.

Attempt. An option is to use reflection (unsafe) to find out the Method to call

Usage. Create a constant for every method in the "listener" interface and use it as an argument

interface Updatable {
  void update();
  Method UPDATE = method(Updatable.class, "update");
}
//anywhere
spot(UPDATE);

using this util function

static public @Nullable Method method(Class<?> of, String name, Class... params) {
  try {
    return of.getDeclaredMethod(name, params);
  }
  catch(Exception e) {/*...*/}
}

Questions. Is there a

  1. safer
  2. simpler

way to get reflect.Methods in (< 8) java ?

Upvotes: 0

Views: 120

Answers (1)

GotoFinal
GotoFinal

Reputation: 3695

You can just use normal functional classes to do this in java 7, it's not pretty but works fine, and if you want to make it prettier you can use something like https://github.com/luontola/retrolambda that will allow you to use lambdas in java 7 that will be compiled to anonymous inner classes.

Listener listenerMethod = new Listener() {
    @Override
    public void onEvent() {
        updatable.update();
    }
});
// anywhere, or in that "spot" method:
listenerMethod.onEvent();

And with retrolambda just

Listener listenerMethod = () -> updatable.update();

or something similar depending how your system looks like.

Upvotes: 0

Related Questions