0

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 ?

7
  • 1
    Why did you not make use of anonymous inner classes instead of lambda expressions? You are correct with your assumption, that reflection is slow for such use.
    – Glains
    Commented Mar 1, 2020 at 15:16
  • Just use something like that: github.com/luontola/retrolambda
    – GotoFinal
    Commented Mar 2, 2020 at 20:45
  • @Holger you are right, I removed the misleading java 8 code!
    – user12026681
    Commented Mar 3, 2020 at 16:57
  • 2
    Actually, I do not understand the problem you are trying to solve. What are you trying to achieve? You talk a lot about how you want to do something but not what you are trying to achieve. This seems to be an instance of the XY problem. I don't get your brief explanation about interfaces and callbacks. I think an MCVE instead of an incoherent set of isolated code snippets would help tremendously.
    – kriegaex
    Commented Mar 6, 2020 at 3:00
  • 1
    Just use normal anonymous classes (or lambdas using this retrolambda linked above) and register a function to call each of this methods somewhere, then you don't need any reflections
    – GotoFinal
    Commented Mar 6, 2020 at 16:34

1 Answer 1

0
+50

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.

1
  • in my case: spot(new Signal<Updatable>(){@Override public void spot(Updatable u){ u.update(); }});
    – user12026681
    Commented Mar 7, 2020 at 7:08