How to get string name of a method in java?

前端 未结 7 707
梦谈多话
梦谈多话 2020-11-29 06:10

How can I find out through reflection what is the string name of the method?

For example given:

class Car{
   public void getFoo(){
   }
}

7条回答
  •  甜味超标
    2020-11-29 06:36

    With Java 8, you can do this with a few lines of code (almost) without any additional libraries. The key is to convert your method into a serialisable lambda expression. Therefore, you can just define a simple interface like this:

    @FunctionalInterface
    public interface SerializableFunction extends Function, Serializable {
      // Combined interface for Function and Serializable
    }
    

    Now, we need to convert our lambda expression into a SerializedLambda object. Apparently, Oracle does not really want us to do that, so take this with a grain of salt... As the required method is private, we need to invoke it using reflections:

    private static final  String nameOf(SerializableFunction lambda) {
      Method findMethod = ReflectionUtils.findMethod(lambda.getClass(), "writeReplace");
      findMethod.setAccessible(true);
    
      SerializedLambda invokeMethod = (SerializedLambda) ReflectionUtils.invokeMethod(findMethod, lambda);
      return invokeMethod.getImplMethodName();
    }
    

    I'm using Springs ReflectionUtils class here for simplicity, but you can of course replace this by manually looping through all superclasses and use getDeclaredMethod to find the writeReplace method.

    And this is it already, now you can use it like this:

    @Test
    public void testNameOf() throws Throwable {
      assertEquals("getName", nameOf(MyClassTest::getName));
    }
    

    I haven't checked this with Java 9s module system, so as a little disclaimer it might be more tricky to do this with more recent Java versions...

提交回复
热议问题