0

What to replace foo() with?

class MethodIteration {
  public static void main(String[] args) {
    for (MyFuncInt m : new MyFuncInt[] { Class1::method, Class2::method })
      System.out.println(m.getClass().foo()); // want Class1, Class2 etc here
  }
}

Sorry about brevity. Mobile device ;)

I don't think it's a duplicate of mentioned question since I want to get the name while outside the class containing the static method. If I try m.getClass().getName() I get "MethodIteration$$Lambda$1:[someHash]".

carlsb3rg
  • 752
  • 6
  • 14

1 Answers1

0

I'm afraid you can't. The calls to Class1::method, Class2::method are wrapped inside a lambda closure that implements MyFuncInt, which has no methods to access the wrapped class (it's not even a declared field of the lambda class).

I'd say you can't use a functional interface. You'd have to make a functor to which you pass a reference to the class (or just a string with the class name), so you can retrieve it later:

class MyFunctor implements MyFuncInt {

    public final Class<?> clazz;
    private final MyFuncInt func;

    public MyFunctor(Class<?> clazz, MyFuncInt func) {
        this.clazz = clazz;
        this.func = func;
    }

    @Override
    public void doSomething() {
        func.doSomething();     
    }
}

Then instantiate like:

new MyFunctor(Class1.class, Class1::method);
Jorn Vernee
  • 31,735
  • 4
  • 76
  • 93