Dynamic invocation methods in the class

  • Java method call, there are two classes: static methods can be used directly for the class name to call for non-static method call must use the object class.
  • Key Technology

  Method class provides the classes and interfaces, a single method (the method and how to access) information, may be reflected in the class or method is an instance method (a method including abstract).

    The method the following statement

    public Object invoke(Object obj,Object... args) throws Exception;

    Parameter Description

  1. obj: method is called from the underlying object
  2. Parameters for the method call

For private methods, we must first ensure that accessible mark visibility

  • designing process
public class MethodTest {
    public static void main(String[] args) {
        System.out.println("调用Math类的静态方法sin()");
        try {
            Method sin = Math.class.getDeclaredMethod("sin",Double.TYPE);
            Double sin1 = (Double) sin.invoke(null,Integer.valueOf(1));
            System.out.println("1的正弦值为:" + sin1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
}
View Code

 

Guess you like

Origin www.cnblogs.com/cglib/p/11512793.html