There are three classes of field,method,constructor in the Java.lang.reflect package. Describes the domain, method, constructor, respectively. Reference API, a description of these three classes.
Use reflection profiling objects at run time, if you are accessing private or private methods, private constructors, Will throw illegalaccessexception. Because the default behavior of the reflection mechanism is restricted to Java access control, however, if a Java program is not under the control of the security manager, access control can be overridden. To achieve this, the Setaccessible method of the Field,method,constructor object needs to be invoked, and the Setaccessible method is a method of the AccessibleObject class, which is Field,method, The public superclass of the constructor class.
Setaccessible (TRUE);
Do not use reflection too much: Destroy class encapsulation; low efficiency; The compiler is not easy to find errors and will be found at runtime.
I use reflection, is to write unit test code, the analysis of the running object, change the private domain of objects, etc., to achieve the test requirements of coverage.
The following provides a code case:
Test class: public class runbing ... {
private String name;
private int age;
public String sex;
Public runbing () ... {
}
Private runbing (String name) ... {
THIS.name = name;
}
public void SetName (String name) ... {
THIS.name = name;
}
public void Setage (int age) ... {
This.age = age;
}
Public String getName () ... {
return name;
}
public int getage () ... {
return age;
}
Public String run () ... {
Return to "Run method";
}
Private String Add () ... {
Return "Add Method";
}
}
Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import Java.lang.reflect.Constructor;
public class Reflecthelp ... {
/** *//**
* Get the instance through the constructor
* @param fully qualified name of the ClassName class
* @param the parameter types of the Intargsclass constructor
* @param parameter values of the Intargs constructor
*
* @return Object
*/
public static Object Getobjectbyconstructor (String classname,class[] intargsclass,object[] intargs) ... {
Object returnobj= null;
Try ... {
Class ClassType = Class.forName (className);
Constructor constructor = Classtype.getdeclaredconstructor (Intargsclass); Find the specified construction method
Constructor.setaccessible (TRUE);//Set up security check, access private constructor must
Returnobj = Constructor.newinstance (Intargs);
catch (Nosuchmethodexception ex) ... {
Ex.printstacktrace ();
&