How do I invoke a Java method when given the method name as a string?

前端 未结 21 2076
耶瑟儿~
耶瑟儿~ 2020-11-21 04:50

If I have two variables:

Object obj;
String methodName = \"getName\";

Without knowing the class of obj, how can I call the met

21条回答
  •  执笔经年
    2020-11-21 05:23

    If you do the call several times you can use the new method handles introduced in Java 7. Here we go for your method returning a String:

    Object obj = new Point( 100, 200 );
    String methodName = "toString";  
    Class resultType = String.class;
    
    MethodType mt = MethodType.methodType( resultType );
    MethodHandle methodHandle = MethodHandles.lookup().findVirtual( obj.getClass(), methodName, mt );
    String result = resultType.cast( methodHandle.invoke( obj ) );
    
    System.out.println( result );  // java.awt.Point[x=100,y=200]
    

提交回复
热议问题