Current location - Quotes Website - Personality signature - About calling a method in a class with java reflection and executing it
About calling a method in a class with java reflection and executing it
To use reflection in Java, you must first obtain the corresponding class object. In Java, there are three ways to obtain class objects corresponding to classes.

1. Class properties of the class.

2. Obtained by the getClass () method of the class instance.

3. Obtained by the method of Class.forName (string class name).

For example, there is a class calculator under the package now.

Public? Class? Calculator {

Public? Double? Plus (double? Score 1, double? Score 2){

Return? score 1? +? score2

}

Public? Invalid? print(){

system . out . println(" OK ");

}

Public? Static electricity Double? mul(double? Score 1, double? Score 2){

Return? score 1? *? score2

}

} public? Class? Calculator test? {

Public? Static electricity Invalid? main(String[]? args)? Throwing? Exceptions? {

//Yes. Class property of the class.

Class & lt calculator & gt? clz? =? Calculator.class

//or through the full path of the class. This method will throw a ClassNotFoundException because it cannot determine whether the passed path is correct.

//Class & lt; Calculator & gt? clz? =? Class.forName("test。 Calculator ");

//or new, and then get it through the getClass () method of the instance.

//Calculator? s? =? New? Calculator ();

//Class & lt; Calculator & gt? clz? =? s . getclass();

// 1.? Gets the mul method with method signature in the class. The first parameter of getMethod is the method name, and the second parameter is the parameter type array of mul.

Method? Method? =? Clz.getMethod("mul ",new? Class[]{double.class,double . class });

//Call? The first parameter of the method is the called object, here it is a static method, so it is null, and the second parameter is the parameter passed to the method to be called.

Object? The result? =? Method.invoke(null, new? Object[]{2.0,2.5 });

//If the method mul is a private private method, calling according to the above method will generate an exception, and its access property must be changed at this time.

//method . set accessible(true); //Private methods can modify their access rights through transmission.

System.out.println (result); //The result is 5.0.

//2.? Gets the non-static methods in the class.

Method? Method _2? =? Clz.getMethod("add ",new? Class[]{double.class,double . class });

//This is an instance method that must be executed on the object.

Object? Result _2? =? Method_2.invoke (new? Calculator (),? New? Object[]{2.0,2.5 });

system . out . println(result _ 2); //4.5

//3.? Gets the method print without method signature.

Method? Method _3? =? Clz.getMethod("print ",new? class[]{ });

Object? Result _3? =? Method_3.invoke (new? Calculator (),? null); //result_3 is null, and this method does not return a result.

}

}