Introduction to the Java reflection mechanism
The Reflection API allows you to get the internal structure of the program at run time. The dynamic proxies provided in the reflection API can natively implement the method interception functionality in AOP. The internal structure of the Java class is obtained by reflection and then applied, and the same effect is applied directly to the class, but the additional flexibility of running time is provided. One of the biggest drawbacks of reflection is poor performance. For the same operation, the time required to use the reflection API is approximately one or two orders of magnitude slower than the direct use. Consider using the reflection API at the right time.
Basic usage
There are two main functions of the Java reflection mechanism. The first major function is to get the internal structure of the program's re-run time. Only a small amount of code is needed to facilitate the internal structure of a Java class, including construction methods, declared domains, and defined methods. The second major function is to manipulate a Java class at runtime. You can dynamically create an object of a Java class, get the value of a domain, and invoke a method. The operations of classes and objects written in the Java source code can be implemented by reflection.
For example, there is now a simple Java class:
class MyClass { public int count; public MyClass(int start) { count = start; } public void increase(int step) { count += step; }}
It is very simple to manipulate classes and their objects through the general approach and the reflection API.
MyClass myClass = new MyClass(0);myClass.increase(2);System.out.println("Normal -> " + myClass.count);try { Counstructor constructor = MyClass.class.getConstructor(int.class); //获取构造方法 MyClass myClassReflect = constructor.newInstance(10); //创建对象 Method method = MyClass.class.getMethod("increase", int.class); //获取方法 Field field = MyClass.class.getField("count"); //获取域,也就是变量 System.out.println("Reflect -> " + field.getInt(myClassReflect)); //获取域的值} catch (Exception e) { e.printStackTrace();}
The above example uses four reflective APIs:getconstructor (), newinstance (), GetMethod (), and GetField (). It is worth noting some of the considerations of the GetMethod method. Look at the following example:
Import Java.lang.reflect.constructor;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.method;class Pet {private int age;private String name;public void Eat () {System.out.println ("eat .... .");} private void Sound () {System.out.println ("sound .....");}} Class Dogge extends Pet {private String gender;public void Run () {System.out.println ("Run ...");} @Overridepublic void Eat () {System.out.println ("eat meat ...");} private void Bark () {System.out.println ("Woo ..."); Public Dogge () {}public Dogge (String gender) {This.gender = gender;}} public class Javatest{public static void Main (string[] args) throws Instantiationexception, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, SecurityException, nosuchmethodexception {Class<?> C1 = do Gge.class; Constructor<?>[] C = c1.getconstructors (); Dogge D1 = (Dogge) c[1].newinstance ("Heheda"); The/** * Eat method is the public method after inheriting class overrides * can be called through reflect. */Method Eat = C1.getmethod ("Eat"); Eat.invoke (D1); /** * The sound method is the private method of the subclass, which cannot be called through a normal access channel but can be called through the reflect channel (like here, where the direct reflect is not possible), as in the next example. *///method Sound = C1.getdeclaredmethod ("sound"); Sound.invoke (D1); The/** * Bark method is private in the inheriting class * here, if the method is reflect with the GetMethod () method, it is not available, the reason behind * notice to use the Setaccessible method, because it is the private method, you need to To give permission. */Method Bark = c1.getdeclaredmethod ("bark"); Bark.setaccessible (TRUE); Bark.invoke (D1); /** * Run method in inheriting class, is public method * Direct reflect can */method run = C1.getmethod ("Run"); Run.invoke (D1); }} The result of the program is: Eat Meat.....woo.....run .....
The above example illustrates the ability to call the child class public through the normal reflect, the parent class public,private (note that the permission to set the response Setaccessible (true)). The following explains why the private method of the parent class cannot be obtained directly from the GetMethod method, but is reflected by the Getdeclaredmethod () method. Let's take a look at the introduction to GetMethod () in the official documentation:
/** * Returns A method object that reflects the specified public * member Method of the class or interface represented by This * Class object. The name parameter is a * String specifying the simple name of the desired method. The * parametertypes parameter is a array of Class * objects that identify the method ' s formal parameter types, in Declar Ed * order. If parametertypes is null, it was * treated as if it were an empty array. * Let C being the class represented by this object: * c are searched for any matching methods. If no matching * method is found, the algorithm of step 1 are invoked recursively on * the superclass of C. * IF No method is found in step 1 above, the superinterfaces of C * is searched for a matching method. If any such method was found, it is reflected. * * To find a matching method in a class c: If C declares exactly one * public method with the specified name and exactly the same formal * parameter types, which is T He method refLected. If more than one such * method was found in C, and one of the these methods have a return type that was * more specific than any Of the others, that's method is reflected; * Otherwise one of the methods is chosen arbitrarily. * */public Method GetMethod (String name, Class<?> .... parametertypes) throws Nosuchmethodexception, securityexcept Ion {//Be very careful the stack depth of this//checkmemberaccess call for security reasons//See java.la Ng. Securitymanager.checkmemberaccess checkmemberaccess (Member.public, Classloader.getcallerclassloader ()); Two methods appear in this line of divergence method method = GETMETHOD0 (name, parametertypes); if (method = = null) {throw new Nosuchmethodexception (GetName () + "." + name + argumenttypestostring (parametertypes )); } return method; Here we call the native method GetMethod0 method, continue to trace the code can be found: Private Method getMethod0 (String name, class[] parametertypes) {//Note:the in Tent is, the search algorithm this routine//uses being equivalent to thE ordering imposed by//Privategetpublicmethods (). It fetches only the declared//public methods for each class, however, to reduce the//number of Method objects wh Ich has to being created for the//common case where the method being requested are declared in//the class which is Being queried. Method res = null; Search declared public methods key place, and the following Getdeclaredmethod method can be compared, the problem appears in the method of the first parameter of the different, here is true, The Getdeclaredmethod method here has a parameter of false. if (res = Searchmethods (Privategetdeclaredmethods (True), name, PA rametertypes)) = null) {return res; }//Search superclass ' s Methods if (!isinterface ()) {Class c = getsuperclass (); if (c! = null) {if (res = C.GETMETHOD0 (name, parametertypes)) = null) {return res; }}}//Search superinterfaces ' methods class[] interfaces = Getinterfaces (); for (int i = 0; I < interfaceS.length; i++) {Class c = interfaces[i]; if (res = C.GETMETHOD0 (name, parametertypes)) = null) {return res; }}//not found return null;}
Below is an introduction to Getdeclaredmethod () :
/** * Returns A method object that reflects the specified * declared Method of the class or interface represented by this * Class object. The name parameter is a * String that specifies the simple name of the desired * method, and the Parametertypes parameter is a array of * Class objects that identify the method's formal parameter * types, in declared order. If more than one method with the same * parameter types are declared in a class, and one of the these methods have a * return Ty PE that's more specific than any of the others, and that's method is * returned; Otherwise one of the methods is chosen arbitrarily. * */public Method Getdeclaredmethod (String name, Class<?> .... parametertypes) throws Nosuchmethodexception, Securi tyexception {//Be very careful the stack depth of this//checkmemberaccess call for security reasons//See Java.lang.SecurityManager.checkMemberAccess checkmemberaccess (member.declared, Classloader.getcallerclassloader ( )); There are differences between the two methods in this line, calledis Privategetdeclaredmethods (false), so we need to investigate the method further. Method method = Searchmethods (Privategetdeclaredmethods (false), name, parametertypes); if (method = = null) {throw new Nosuchmethodexception (GetName () + "." + name + argumenttypestostring (parametertypes )); } return method;
entered the definition of the privategetdeclaredmethods () method, where the code is as follows:
Returns an array of "root" methods. These Method objects must not//be propagated to the outside world, but must instead is copied//via REFLECTIONFACTORY.COP Ymethod.//accepts the name of the passed-in parameter as publiconly, so you can see why the GetMethod () method cannot reflect the private method in the class. Private method[] Privategetdeclaredmethods (Boolean publiconly) {checkinitted (); method[] res = NULL; if (usecaches) {clearcachesonclassredefinition (); if (publiconly) {//The code inside this if is the code executed by the GetMethod () method call, all public methods are returned with the IF (declaredpublicmethods! = NULL) {res = (method[]) declaredpublicmethods.get (); }} else {The method inside the//else is executed when the Getdeclaredmethod method is called. All defined methods are returned. if (declaredmethods! = null) {res = (method[]) declaredmethods.get (); }} if (res! = null) return res; }//No cached value available; Request value from VM res = GETDECLAREDMETHODS0 (publiconly); if (usecaches) {if (publiconly) { Declaredpublicmethods = new SoftReference (res); } else {declaredmethods = new SoftReference (res); }} return res;}
The difference between the GetMethod () and the Getdeclaredmethod () method should be understood almost as you see here.
Because of the specificity of the array, the array class provides a series of static methods for creating an array and manipulating and accessing its elements. For example, do the following:
Object array = Array.newInstance(String.class,10); //等价 new String[10]Array.set(array,0,"Hello");Array.set(array, 1, "world");System.out.println(Array.get(array, 0));
The Java Reflection API can be used to bypass Java's default access control checks, such as the ability to directly get the value of the object's private domain or call a private method. You only need to call the Setaccessible method and set to True after you have obtained the object for the constructor, field, and method classes. With this mechanism, it is convenient to get the internal state of the program at run time.
Java Reflection Mechanism Learning notes