What is reflection? Reflection is the mapping of the various components in the bytecode into the corresponding Java class, Java reflection technology since JDK1.1 has emerged, most popular frameworks have adopted this technology, it is important to see, this article will detail my research on the Java Reflection technology.
Class that represents the byte-code object
All classes in Java have their own unique bytecode, and when the program calls that class, the JVM loads the bytecode into memory . In Java, there are three main methods to get the corresponding bytecode object.
- obtained by the GetClass () method of an instance of the class, such as Class Clazz=new date (). GetClass () Gets the bytecode object of the date class.
- Obtained through the class property of the classes. such as class Clazz=string.class or class Clazz=system.class. It is important to note that there are eight main types in Java (byte,char,short,int,long,float,double, Boolean) and a return type void have the class attribute, and both return their own bytecode object. such as Int.class,boolean.class,float.class and so on. Where the Type property of their wrapper class also returns the byte code of their main type, for example, Int.class==integer.type is True,void.class==void.type true;
- Obtained by means of the class forname () method, such as Class Clazz=class.forname ("Java.lang.Math");
In Java, the class Isprimitive () method can be used to determine whether the current byte code is the primary type, and Isenum () determines whether the bytecode is an enumeration class. IsArray () Determines whether the bytecode is an array type. a class and the array it consists of have different byte codes, such as Int.class==int[].class, which is blocked by the compiler at compile time because the compiler finds that the object on both sides of the comparison is not on an inheritance tree branch. Only arrays of the same type and dimension will share a single bytecode object , such as int a1[]=new int[1], a2[]=new int[5];int a3[][]=new int[2][5];a1.getclass () = = A2.getclass () is True,a2.getclass () ==a3.getclass () is false;
Represents the constructor of the builder
In Java, the GetConstructor () and GetConstructors () methods are used to return the builders of a public and all public access levels, while the Getdeclaredconstructor () and Getdeclaredconstructors () return one of the builders and all the builders in all the builders. Constructor can create an instance of the class by using the Newinstance () method. As shown in the following example
Class Clazz=string.class;
Constructor Cs=clazz.getconstructor (Stringbuffer.class);
String s= (String) cs.newinstance (new StringBuffer ("abc"));
The code above is equivalent to
String S=new string (new StringBuffer ("abc"));
Also shown in the following example
String obj=string.class.getconstructor (). newinstance ();
The code above is equivalent to
String Obj=new string ();
If you want to get all the builders you can do it the following way.
Constructor[] Allcons=string.class.getdeclaredconstructors ();
for (Construcotr con:allcons)
System.out.println (Con.getname ());
In addition to the newinstance () method provided in the constructor class, there is a similar newinstance () method in class, because we can generate the object of the bytecode directly when we get the byte-code object.
ArrayList al= (ArrayList) ArrayList.class.newInstance (); In fact, the step to get the builder object is encapsulated in the class's Newinstance () method.
Public Object newinstance ()
{
This.getconstructor (). newinstance ();
}
field to represent fields
The class class provides fields in GetField () and GetFields () for one and all public levels in fields of the public level,Getdeclaredfield () and Getdeclaredfields () Get one and all of the fields in all fields.
If a field is of an array type, then it needs to be java.lang.reflect.Array to be reflected. There are times when you get a field with a private access level, and if you want to read and set the value at this time, you will typically report a run-time exception, but Java reflection technology is not powerless, and reflection can bypass some of the compiler's limitations for "violent reflection." Just set the field's Setaccessible () to true at this point.
Package Net.csdn.blog; Public class Reflectclass { publicint data[]=newint[]{1,3,5,7,9}; The field of the array type private String name= "field one"; Private Level field float f=2.6f;}
The following reflects the fields in the Reflectclass class
PackageNet.csdn.blog;ImportJava.lang.reflect.Array;ImportJava.lang.reflect.Field; Public classReflectclasstest { Public Static voidMain (string[] args) {Reflectclass rc=NewReflectclass (); Try{handlereflect (RC); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(illegalaccessexception e) {e.printstacktrace (); } } Private Static voidHandlereflect (Object obj)throwsillegalargumentexception, illegalaccessexception{Class clazz=Obj.getclass (); Field fields[]=Clazz.getdeclaredfields (); for(Field field:fields) { if(! Field.isaccessible ()) field.setaccessible (true); Object fieldobj=field.get (obj); // get the value of a field if(Field.gettype (). IsArray ()) {//What happens when the processing field is an array intLen=array.getlength (Fieldobj);//get the length of the array for(inti=0;i<len;i++) {System.out.println (Array.get (Fieldobj, i));//print each element in an array } }Else{ if(Field.gettype () = =float.class) field.set (obj,5.2F);//value of the Set Value fieldObject o=field.get (obj); System.out.println (o); } } }}
Method for representing member methods
The class class also provides GetMethod (), GetMethods () for methods that get the public level and all public, and Getdeclaredmethod () and Getdeclaredmethods () method is used to obtain any access level of a method and any access level method.
PackageNet.csdn.blog; Public classReflectMethod { Public voidSayHello () {System.out.println ("Hello World"); } Public voidPrintArray (Object obj[]) { for(Object o:obj) System.out.println (o); } Publicstring Getreversemsg (String msg) {return NewStringBuffer (msg). Reverse (). toString (); }}
Reflection on a ReflectMethod class
PackageNet.csdn.blog; Importjava.lang.reflect.InvocationTargetException; ImportJava.lang.reflect.Method; Public classReflectmethodtest { Public Static voidMain (String argsp[]) {ReflectMethod RM=NewReflectMethod (); Try{ReflectMethod (RM); } Catch(Exception e) {e.printstacktrace (); } } Private Static voidReflectMethod (Object obj)throwsSecurityException, Nosuchmethodexception, IllegalArgumentException, Illegalaccessexception, invocationtargetexception{ Class clazz =Obj.getclass (); Method=clazz.getdeclaredmethod ("SayHello", null ); // get SayHello () method Method.invoke (obj, null ); //Execute this method Method=clazz.getdeclaredmethod ("PrintArray", object[].class ); Method.invoke (obj, (Object)NewObject[]{"This is a joke", "Csdn Blog"});//The transformation should be made here to tell the Yi not to follow the JDK1.4 approach.Method=clazz.getdeclaredmethod ("Getreversemsg", String.class ); String msg= (String) method.invoke (obj, "ABCDEFG" ); SYSTEM.OUT.PRINTLN (msg); } }
Reflection on the inner class
The information on the web for how to use reflection to map out the internal class is very small, I deliberately spent one hours of research for a while, the following results are written below.
The class itself also provides methods for obtaining internal class bytecode, getclasses and getdeclaredclasses (), where getclasses () can only get internal classes that have access level public. and getdeclaredclasses () can get all the declared inner classes.
Since the inner class can be divided into instance inner class, Static inner class, anonymous inner class, the aforementioned Getclasses () and getdeclaredclasses () can only get the instance inner class and static inner class, for the following two kinds of circumstances, but there is nothing to do, To do this, you need to take some special measures to perform reflection operations on anonymous inner classes.
PackageNet.csdn.blog; Public classReflectinnerclass { PublicRunnable Ta=NewRunnable () { Public voidrun () {System.out.println ("The method in the anonymous inner class was executed."); } }; Private classinner2{ PublicInner2 () {System.out.println ("The Inner2 class was instantiated."); } } classinner3{ PublicInner3 () {System.out.println ("The Inner2 class was instantiated."); } } Public classinner1{ PublicInner1 () {System.out.println ("The Inner1 class was instantiated."); } }}
The inner class is reflected below
PackageNet.csdn.blog; Importjava.lang.reflect.InvocationTargetException; ImportJava.lang.reflect.Modifier; Public classReflectinnerclasstest { Public Static voidMain (String args[]) {Reflectinnerclass ric=NewReflectinnerclass (); Try{Reflectinnerclass (RIC); } Catch(Exception e) {e.printstacktrace (); } } Private Static voidReflectinnerclass (Reflectinnerclass Ric)throwsinstantiationexception, Illegalaccessexception, SecurityException, Nosuchmethodexception, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, nosuchfieldexception {Class clazz
=Ric.getclass (); Class classes[]=clazz.getdeclaredclasses (); for(Class c:classes) {//to reflect a member's inner class intI=c.getmodifiers (); String s=modifier.tostring (i); if(S.contains ("Static"))//handling of static internal classesc.getconstructor (). newinstance (); Else //handling of instances inner classesC.getconstructor (Ric.getclass ()). Newinstance (RIC); } //because the anonymous inner class does not have a builder, the instance cannot be created, nor can it directly access the methods in it, but the method or member variable in which the second is executed in the following way. Runnable r= (Runnable) (Clazz.getfield ("Ta")). Get (RIC)); R.run (); } }
This article was reproduced from: http://blog.csdn.net/helloapps/archive/2010/07/06/5716604.aspx
Java Reflection Technology