简体   繁体   中英

get java.lang.reflect.Method safely

Similar interface s 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.Method s in (< 8) java ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM