1. Java Reflection mechanism (noun interpretation)
In the dynamic operation of a class, all the properties and methods of the class can be obtained through its path for any class, and the function of dynamically acquiring class properties is called the reflection mechanism of java.
2, the role of the Java reflection mechanism
A, can judge the class that the object belongs to
b, can get all the properties and methods of any class
C, the ability to construct arbitrary classes of objects, the ability to invoke arbitrary object methods
D, generate dynamic proxy (the dynamic proxy of the reflection mechanism is elaborated in the subsequent Java Dynamic Agent chapters)
3. Java API
Gets the path name of the object Test test=new test ();//Get Class object Class<?> Testclass=test.getclass (); Class<?> clazz =class.forname ("Path to Java class packages"); Class<?> clazz2=test.class;//Gets the name of the object string Testclassname=testclass.getname ();//Gets the class object class<?> Clazz =class.forname ("Path to Java class package");//Get parent class class<?> ParentClass =clazz.getsuperclass ();//Get all interfaces of class class<? > infes[] =clazz.getinterfaces ();//Instantiate Class object Class<?> class1=classforname ("Com.demo.User"); User user= (user) class1.newinstance ();//Get all constructors for class constructor constructors[]=class1.getconstructors ();// Get all methods of the class method method[] =class1.getmethods ();//Call the method in the class Method=class1.getmenthod ("Method1"); Menthod.invoke ( Class.newinstance ());//Get property value field[] Fields=class1.getdeclaredfields ();//This class field[] fields=class1.getfields ();// Gets the implemented interface or parent class attribute//get permission type int mo =fields[0].getmodifiers (); String priv=modifier.tostring (MO);//Gets the attribute type class<?> type=field[0].gettype (); String typename=type.getname ();//Operation Attribute object Obj=class1.newinstance (); Class1.getdeclaredfields ("xxProperty "). Setaccessible (True). Set (obj," xx new attribute ");
4. Application examples
PackageCom.demo;ImportJava.lang.reflect.Method;Importjava.util.ArrayList; Public classTestrefect { Public Static voidMain (string[] args)throwsException, nosuchmethodexception {ArrayList list=NewArrayList (); Class<?> clazz=List.getclass (); Method Method=clazz.getmethod ("Add", Object.class); Method.invoke (list,"Reflection");//Run Method Object valuesSystem.out.println (List.get (0)); }}
//Get and modify the information of the array
PackageNet.xsoftlab.baike;ImportJava.lang.reflect.Array; Public classTestreflect { Public Static voidMain (string[] args)throwsException {int[] temp = {1, 2, 3, 4, 5 }; Class<?> demo =Temp.getclass (). Getcomponenttype (); System.out.println ("Array type:" +demo.getname ()); System.out.println ("Array Length" +array.getlength (temp)); System.out.println ("The first element of the array:" + array.get (temp, 0)); Array.set (temp,0, 100); System.out.println ("The first element of the array after modification is:" + array.get (temp, 0)); }}
To modify the size of an array
PackageNet.xsoftlab.baike;ImportJava.lang.reflect.Array; Public classTestreflect { Public Static voidMain (string[] args)throwsException {int[] temp = {1, 2, 3, 4, 5, 6, 7, 8, 9 }; int[] Newtemp = (int[]) Arrayinc (temp, 15); Print (newtemp); String[] ATR= {"A", "B", "C" }; String[] str1= (string[]) arrayinc (ATR, 8); Print (STR1); } //Modifying the size of an array Public StaticObject Arrayinc (Object obj,intLen) {Class<?> arr =Obj.getclass (). Getcomponenttype (); Object NEWARR=array.newinstance (arr, Len); intCO =array.getlength (obj); System.arraycopy (obj,0, NEWARR, 0, CO); returnNEWARR; } //Print Public Static voidprint (Object obj) {Class<?> C =Obj.getclass (); if(!C.isarray ()) { return; } System.out.println ("Array length is:" +array.getlength (obj)); for(inti = 0; I < array.getlength (obj); i++) {System.out.print (Array.get (obj, i)+ " "); } System.out.println (); }}
Using Reflection for Factory mode
PackageNet.xsoftlab.baike;InterfaceFruit { Public Abstract voideat ();}classAppleImplementsFruit { Public voideat () {System.out.println ("Apple"); }}classOrangeImplementsFruit { Public voideat () {System.out.println ("Orange"); }}classFactory { Public StaticFruit getinstance (String ClassName) {fruit F=NULL; Try{f=(Fruit) class.forname (ClassName). newinstance (); } Catch(Exception e) {e.printstacktrace (); } returnF; }}/*** For normal Factory mode when we add a subclass, we need to modify the factory class accordingly. When we add a lot of sub-classes, it can be very troublesome. * Java Factory mode can be referenced *Http://baike.xsoftlab.net/view/java-factory-pattern* * Now we use the reflection mechanism to implement Factory mode, you can add any number of subclasses without modifying the factory class. * * But it's still a bit cumbersome to know the full package name and class name, which can be done using the properties configuration file. * * Java read the Properties configuration file method can refer to *Http://baike.xsoftlab.net/view/java-read-the-properties-configuration-file * * @authorxsoftlab.net*/ Public classTestreflect { Public Static voidMain (string[] args)throwsException {fruit F= Factory.getinstance ("Net.xsoftlab.baike.Apple"); if(F! =NULL) {f.eat (); } }}
Java reflection mechanism