What is the reflection mechanism?
The reflection mechanism is in the running state, and for any class, it is possible to know all the properties and methods of the class.
, for any object, can invoke one of his methods and properties, this dynamically acquired information and
The ability to dynamically invoke the methods of an object is called the reflection mechanism of the Java language.
What can the reflection mechanism do?
The reflection mechanism mainly provides the following functions
√ Determine the class to which any object belongs at run time
√ Construct an object of any class at run time
√ Determine the properties and methods of any class at run time
√ Methods for invoking an object at run time
√ Generating dynamic proxies
Get the full package name and class name from an object
Package Com.hzg; Public class Testreflect { publicstaticvoidthrows Exception { New testreflect (); System.out.println (Testreflect.getclass (). GetName ()); // result Com.hzg.TestReflect }}
Get the complete properties, methods, and objects through an object
Class clazz = person. class (); // 1. Create the run-time class person object for the Clazz object Person p = (person) clazz.getinstance (); // 2. Invoking the specified properties of the runtime through reflection Filed f1 = Clazz.getfield ("name"); F1.set (P,"Liudehua"); // 3. Call the runtime's specified method through reflection Method m1 = Clazz.getmethod ("Show", String. Class); M1.invoke (P,"CHN");
Note: Class is not a keyword Class,class is a class name, and class is a keyword that identifies a class
Get an instance of class (3 ways)
① invokes the. Class property of the run-time class itself
Class clazz = Person.class;
② is obtained through the object of the runtime class
Person p = new person ();
Class clazz = P.getclass ();
③ is obtained by the static method of class
Class clazz = Class.forName ("Com.hzg.TestReflect");
PackageCom.hzg; Public classTestreflect { Public Static voidMain (string[] args)throwsException {Class<?> Class1 =NULL; Class<?> Class2 =NULL; Class<?> CLASS3 =NULL; //① static methods (typically in this form)Class1 = Class.forName ("Com.hzg.TestReflect"); //② Object acquisition for run-time classesClass2 =Newtestreflect (). GetClass (); //The ③ class itself. Class PropertyCLASS3 = Testreflect.class; System.out.println ("Class name" +class1.getname ()); System.out.println ("Class name" +class2.getname ()); System.out.println ("Class name" +class3.getname ()); }} Gets the parent class of an object with the implemented interface
1 PackageCom.hzg;2 Importjava.io.Serializable;3 Public classTestreflectImplementsSerializable {4 Private Static Final LongSerialversionuid = -2862585049955236662l;5 Public Static voidMain (string[] args)throwsException {6Class<?> clazz = Class.forName ("Com.hzg.TestReflect");7 //Get parent class8class<?> ParentClass =Clazz.getsuperclass ();9System.out.println ("Clazz's parent class is:" +parentclass.getname ());Ten //Clazz's parent class is: Java.lang.Object One //get all the interfaces Aclass<?> intes[] =clazz.getinterfaces (); -System.out.println ("Clazz implements the interface is:"); - for(inti = 0; i < intes.length; i++) { theSystem.out.println ((i + 1) + ":" +intes[i].getname ()); - } - } -}
What can I do with a class instance?
① can create objects that correspond to runtime classes
② gets the structure of the complete class that runs the class: Properties, methods, constructors, packages, generics, annotations, exceptions, inner classes.
such as method[] m1 = Clazz.getmethods (): Gets all public methods of the class and parent class
Method[] M1 = Clazz.getdeclaredmethods (): All modifier methods
But without the parent class, only all of the modifier methods in this class
③ call Run is the struct specified in the Class (property, method, constructor)
√ Gets the specified attribute: Field name = Clazz.getfield ("name");
√ Set the specified public property: Name.set (P, "HZG");
√ Set the specified private property:
Field name = Clazz.gedeclaredtfield ("name");
Name.setaccessible (TRUE);
Name.set (P, "HZG");
√ Get the method specified: m1 = Clazz.getmethod ("show");
√ Call the specified method:
Object obj = M1.invoke (p); The return type is the return type of the method
√ Call static method: M1.invoke (Person.class);
√ Call the specified method with parameters:
Method m1 = Clazz.getdeclatedmethod ("Show1", String.class);
Object obj = M1.invoke (P, "HZG");
√ Call constructor: Constructor con = clazz.getdeclaredconstructor ();
√ Call with parametric constructor, consistent with parameter method
Application---Proxy for Java reflection
1, static proxy (interface-based polymorphism implementation of static proxy)
1 Interfaceclothfactory{2 voidProductcloth ();3 }4 //by proxy class5 classNikeclothfactory implements clothfactory{6 @Override7 Public voidProductcloth () {8Sysytem.out.printLn ("Nike factory produces a batch of clothes");9 }Ten } One //proxy class A classProxyfactory implements clothfactory{ - Clothfactory CF; - Publicproxyfactory (Clothfactory CF) { the This. CF =CF; - } - @Override - Public voidProductcloth () { +Sysytem.out.printLn ("Agent class start execution, receive agency fees 1000"); - Cf.productcloth (); + } A } at - Public classtest{ - Public Static voidMain (string[] args) { - //① Creating a Proxied object -Nikeclothfactory Nike =Newnikeclothfactory (); - //② Creating a proxy class object inProxyfactory proxy =Newproxyfactory (Nike); - //③ methods for invoking proxy class objects to Proxy.productcloth (); + } -}
Static Agent Summary:
Both the ① proxy class and the proxy class implement the same interface
The ② proxy class and the proxy class implement the methods in the interface
2. Dynamic proxy (dynamic proxy based on reflection implementation)
1 Interfaceclothfactory{2 voidProductcloth ();3 }4 //by proxy class5 classnikeclothfactory inplements clothfactory{6 @Override7 Public voidProductcloth () {8Sysytem.out.printLn ("Nike factory produces a batch of clothes");9 }Ten } One //① must implement Invocationhandler interface A classMyinvocationhandlerImplementsinvocationhandler{ - //② proxy class for declaring interfaces - Object obj; the //③ Creating a method instantiation proxy class - Publicobject bind (Object obj) { - This. obj =obj; - returnProxy.newproxyinstance ( + Obj.getclass (). Geyclassloder (), -Obj.getclass (). Getinterfaces (), This); + } A //④ method of implementing interface Invacationhandler at //This method implements: When invoking the object method of the proxy class, it will be converted to the calling - @Override - Publicobject Invoke (Object Proxy,method method,object[] args) { -Object ReturnVal =Method.invoke (Obj,args); - returnreturnval (); - } in } - //Call Implementation to Public classtest{ + Public Static voidMain (string[] args) { - //①: Create a Proxied object theNikeclothfactory Nike =Newnikeclothfactory (); * //②: Create a proxy class object $Myinvocationhandler hander =NewMyinvocationhanlder ();Panax NotoginsengClothfactory Proxycloth =(clothfactory) hander.bind (Nike); - //③: Methods for invoking proxy class objects the Proxycloth. Productcloth (); + } A}
And then brother combed the Java Knowledge points-reflection and proxy (17)