The foundation that Java developers must understand--reflection and dynamic proxy

Source: Internet
Author: User

Java's reflection and dynamic proxies are the lower-level knowledge of Java architectures, and beginners may feel less useful, but they do have the most important content used by the Spring framework IOC and AOP. This knowledge is used when we need to develop more basic, more extensive code.

Before we start, let's look at the Java class loading mechanism

JVM and class loading mechanism:

/* 1.JVM: When the Java command is invoked to run a Java program, the command launches a Java Virtual machine process, all threads in the same JVM, all variables in the same process, all using the JVM's memory area * 2.JVM: Run the following two test class methods, Is output 2, because the two test classes are running, two JVM processes are started, and after the process is finished, all of its modifications to class A are lost-the second time the JVM is run, the Class A is initialized again (two Java programs are in different JVM processes and data cannot be shared between different processes) * 3.   Class loading: Refers to the loading of the. class file for the classes into memory, generating the corresponding Java.lang.Class object (class is Java.lang.Class object), from the local file system, the jar file, * Load. class files over the network, dynamically compile and load a source file four ways * 4. Class Connection: Merging the binary data of the class into the JRE, validating, preparing, parsing * 5. Initialization: primarily responsible for initializing class variables ( The JVM is initialized first always java.lang.Object) * 6. Class initialization time: * 6.1 Create an instance of the class (new, reflect create instance, deserialize create instance) * 6.2 Call class method of a class * 6.3 Call class variable of a class or interface, or change to class Volume Assignment * 6.4 Use reflection to create a Java.lang.Class object of a class * 6.5 Initializes a subclass of a class * 6.6 run a main class directly with the Java command * special case See code: Variable */class with final decoration a{ public static int a = 1;static final String str= "I am a good man";  A macro variable, equivalent to a constant, can determine the static final String date = new Date (System.currenttimemillis ()) + "" in the compile-time value; is not a macro variable, compile-time cannot determine the value of STATIC{SYSTEM.OUT.PRINTLN ("Static initialization block: ");}} public class Jvmtest{public static void Main (string[] args) throws classnotfoundexception{/*a a = new A (); a.a++;  System.out.println (A.A); 2*//*system.out.println (A.STR); is not initialized, System.out.println (a.date); Initializes the *///load class and does not perform initialization ClassLoader CL = Classloader.getsystemclassloader (); Cl.loadclass ("JVM.  B "); //!!! Receive the full class name, that is, the need to add the package name, otherwise it will appear classnotfindexceptionSystem.out.println ("Load class completion"); Class.forName ("JVM.  B "); Initializes}}class jvmtest1{public static void Main (string[] args) {A A = new A (); a.a++;  System.out.println (A.A); 2}}


class Loader:

/* * 7. Class Loader: The same class will only be loaded once (a class with its fully qualified name + loader as a unique identifier) *   7.1 Bootstrap ClassLoader: The root ClassLoader, the JVM itself, is responsible for loading the core class *       extendsion ClassLoader: Extension class loader, load custom class library, put under Lib.ext * System       ClassLoader:  class loader loaded under classpath path *       User custom class loader ( Inherit ClassLoader Class) *   class 7.2 Loading mechanism: Overall responsibility, parent class delegate, caching mechanism *    */class classloadertest{public static void Main (string[] args) Throws Ioexception{classloader Systemloader = Classloader.getsystemclassloader (); SYSTEM.OUT.PRINTLN ("System class Loader:" +systemloader); Appclassloader Subclass enumeration<url> em = systemloader.getsystemresources (""); while (Em.hasmoreelements ()) { System.out.println (Em.nextelement ());} ClassLoader Extendloader = Systemloader.getparent (); System.out.println ("Extension class loader:" +extendloader); SYSTEM.OUT.PRINTLN ("Load Path:" +system.getproperty ("Java.ext.dirs")); System.out.println ("extension class Loader's parent class:" +extendloader.getparent ()); NULL root ClassLoader implemented by JVM}}

Reflection: Accessing the details of a class through reflection

Package Invoke;import Java.io.fileinputstream;import Java.io.ioexception;import java.lang.reflect.Constructor; Import Java.lang.reflect.field;import Java.lang.reflect.invocationtargetexception;import Java.lang.reflect.Method ; Import Java.lang.reflect.parameter;import Java.util.hashmap;import java.util.list;import Java.util.Map;import java.util.properties;/* * 1. When a class is not known at compile time or which class the object might belong to, the program can only rely on runtime information to discover the real information of that class and object, and it needs to use reflection * 2. Get the Class object: Each class is loaded after the corresponding Java.lang.Class object is generated, through which the class object can access the information in the JVM, there are three ways to obtain class object * 2.1 class name. class * 2.2 Class.forName (the fully qualified name of the class) * The instance name of the class 2.3. GetClass () * The first two ways are to get class objects through the name of the classes, usually using one, the code is more secure (usually at compile time to check for the existence of the class object to be accessed). Good program performance (no method required) * 3. Get information from class: class provides a number of instance methods to get the details of the corresponding class * 3.1 Gets the class containing the constructor * constructor<t> GetConstructor (class <?>...parametertypes) Gets the specified public constructor * CONSTRUCTOR&LT; >[] GetConstructors () gets all public constructors * constructor<t> Getdeclaredconstructor (class<?> .... parametertypes) gets all access permissions for the specified parameter constructor * CONSTRUCTOR&LT;? >[] Getdeclaredconstructor () constructor for any parameter that gets all access permissions * 3.2 Gets the class contains methods, variables, Annotation, inner classes, etc., see API * 3.3 Java8 also added reflection of method parameters, see Code * /class test{public void replace (String str,map<string,object> list) {}}public class Invoketest {public static void M Ain (string[] args) throws Nosuchmethodexception, securityexception{class<test> clazz = Test.class; Method replace = Clazz.getmethod ("Replace", String.class,map.class); System.out.println ("The number of replace method parameters is:" +replace.getparametercount ()); parameter[] params = replace.getparameters (); int i = 0;for (Parameter p:params) {System.out.println ("+" + (++i) + "parameter Information"); SYSTEM.OUT.PRINTLN ("Formal parameter name:" +p.getname ());    SYSTEM.OUT.PRINTLN ("formal parameter Type" +p.gettype ()); System.out.println ("Generic type" +p.getparameterizedtype ());//Get complete parameters and generic}}}/* * 4. Create Object * 4.1 Use the Class object's newinstance ()  Method creates an object of the corresponding class, requires that the class has a default constructor called (Common) * 4.2 First gets the specified constructor object using the Class object, and then calls the constructor Newinstance () method to create the instance, you can specify the constructor * Object Pool Factory (implements a simple object pool that reads Key-value pairs according to the configuration file, then creates them and puts them into HashMap) */class objectpoolfactory{//ObjectPool, key is the object name, value is the actual object private map<string,object> Objectpool = new hashmap<> ();//create object by reflection private object CreateObject (String ClassName) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception{class <?> clazz = Class.forName (className); return clazz.newinstance ();} Read configuration file initialization object pool private void Initpool (String fileName) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception{try (FileInputStream fis = new FileInputStream (fileName)) {Properties prop = new Properties (); Prop.load (FIS); for (String name:prop.stringPropertyNames ()) {Objectpool.put (Name, CreateObject (Prop.getproperty ( name)));}} catch (IOException e) {e.printstacktrace ();}} External get Reflection Object */* config file prop.txt, put in Project catalog * a = java.lang.String b = Java.util.Date */public object GetObject (String name) {R Eturn objectpool.get (name);} public static void Main (string[] args) throws Classnotfoundexception,securityexception, Instantiationexception, Illegalaccessexception, Nosuchmethodexception,illEgalargumentexception, invocationtargetexception {objectpoolfactory pf = new Objectpoolfactory ();p F.initpool (" Prop.txt "); System.out.println (Pf.getobject ("a")); System.out.println (Pf.getobject ("B"));//Create an instance with the specified constructor class<?> clazz = Class.forName ("Javax.swing.JFrame"); Constructor con = clazz.getconstructor (string.class); Gets the specified parameter constructor object, obj = con.newinstance ("Test Window"); System.out.println (obj);}} /* * 5. Call method: The method object can be used to invoke its specified methods * 5.1 object Invoke (Object Obj,object.   args) obj is the keynote of the method, and args is the parameter of the method * The following program enhances the object pool project above, allowing the value of the member variable of the configuration object to be added to the configuration file, and the object pool factory reads the value of the member variable configured for the object * The value of the member variable is set by the setter method of the object (the spring framework manages the value of the member variable and the dependent object in the configuration file in such a way that it is better decoupled.) This is also how the IOC is implemented) * 5.2 when the corresponding method is called by the Invoke method, Java requires that the program must be called by the permission of the method, and if the program does need to call the private method of an object * The Setaccess of the methods object can be called Ible (True) to cancel access check, Method Field constructor has */class extendobjectpoolfactory{private map<string,object> Objectpool = new hashmap<> ();p rivate Properties config = new Properties ();p ublic void init (String fileName){try (FileInputStream fis = new FileInputStream (fileName)) {config.load (FIS);} catch (IOException e) {e.printstacktrace ();}} Create objects public Object CreateObject (String Clazzname) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception{class<?> clazz = Class.forName (clazzname); Object obj = Clazz.newinstance (); return obj;} Initialize object pool public void Initpool () throws ClassNotFoundException, Instantiationexception, Illegalaccessexception{for ( String Name:config.stringPropertyNames ()) {if (!name.contains ("%")) {Objectpool.put (Name,createobject ( Config.getproperty (name))); Created}}}public Object getObject (String name) {return objectpool.get (name);} Call the corresponding setter method according to the attribute profile public void Initproperty () throws Nosuchmethodexception, SecurityException, Illegalaccessexception, IllegalArgumentException, Invocationtargetexception{for (String name: Config.stringpropertynames ()) {if (Name.contains ("%")) {string[] Objandprop = name.split ("%"); Object target = GetObject (Objandprop[0]); String Mtdname = "Set "+objandprop[1].substring (0,1). toUpperCase () +objandprop[1].substring (1); class<?> Targetclass = Target.getclass (); method = Targetclass.getmethod (Mtdname, String.class); Method.invoke (target, Config.getproperty (name));}}}                                        public static void Main (string[] args) throws ClassNotFoundException, Instantiationexception, Illegalaccessexception, Nosuchmethodexception, SecurityException, IllegalArgumentException, Invocationtargetexc Eption{extendobjectpoolfactory factory = new Extendobjectpoolfactory (); Factory.init ("prop.txt");// Load configuration file Factory.initpool (); Initialize the object pool Factory.initproperty (); System.out.println (Factory.getobject ("a"));}} /* * 6. Access the value of the member variable */class person{private string name;private int age;public string toString () {return "name:" +name+ "Age:" +age; }}class fieldtest{public static void Main (string[] args) throws Nosuchfieldexception, SecurityException, IllegalArgumentException, Illegalaccessexception{person p = new person (); Class<person> CLazz = Person.class;  Field name = Clazz.getdeclaredfield ("name"); Name.setaccessible (true); Set permissions to access private variables Name.set (p, "Lee"); Field age = Clazz.getdeclaredfield ("Age"); Age.setaccessible (true); Age.setint (P, 20); SYSTEM.OUT.PRINTLN (P);}}



Dynamic agent and AOP:

Package Invoke;import Java.lang.reflect.field;import Java.lang.reflect.genericarraytype;import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import Java.lang.reflect.ParameterizedType; Import Java.lang.reflect.proxy;import java.lang.reflect.type;import java.util.map;/* * 1. Proxy provides dynamic proxy classes and dynamic proxy objects for creating one or more interfaces, and the JDK dynamic agent can only create dynamic proxies for excuses * 1.1 static class<?> Getproxyclass (ClassLoader loader, class<?>...interfsaces) * 1.2 static Object newproxyinstance (ClassLoader loader,class<?>[] interface, Invocationhandler h) * Each proxy object generated by the system has a Invocationhandler object associated with it, and each method that executes the proxy object is replaced with the Invoke method * 2 that executes the Invocationhandler object. Use proxy and Invocationhandler to create dynamic proxy objects, see Code */interface student{void Walk (); void SayHello (String name);} Class Myinvocationhandler implements Invocationhandler{public object Invoke (Object proxy, Method method, object[] args) Throws Throwable{system.out.println ("--method being executed" +method); if (args! = null) {System.out.println ("arguments passed in executing method:"); for ( Object Object:args) {SysteM.out.println (object);}} Else{system.out.println ("The method does not pass in any parameters");} return null;}} public class Proxytest{public static void Main (string[] args) {Invocationhandler handler = new Myinvocationhandler (); Student s = (Student) proxy.newproxyinstance (Student.class.getClassLoader (), New Class[]{student.class}, Handler); S.walk (); S.sayhello ("Lee");}} /* * 3. Using dynamic proxies and AOP, the target object implements the same interface as the proxy object that is generated for it, with the same method. Very flexible implementation understanding decoupling, facilitates post-maintenance of code *//* running results: * = = Analog Insertion Method 1== I'm a hound. = = Analog Insertion method 2==== Analog Insert Method 1== I run fast = = Analog Insert method 2== */interface dog{void info ( ); void run ();} If the dynamic proxy is created directly for the interface, then all the method execution bodies are the same, not much meaning, so the interface usually provides one or more implementation class class Gundog implements Dog{public void info () { System.out.println ("I Am a Hound Dog"); public void Run () {System.out.println ("I run Quickly");}} Class Dogutil{public void Method1 () {System.out.println ("= = Analog Insert method 1==");} public void Method2 () {System.out.println ("= = Analog Insert method 2==");}} Class MyInvocationhandler1 implements Invocationhandler{private object Target;public void Settarget (object target) { This.target = target;} public object invoke (object proxy, Method mEthod, object[] args) throws throwable{dogutil util = new Dogutil (); Util.method1 (); Object result = Method.invoke (target, a RGS); Util.method2 (); return result;}} Generates a dynamic proxy instance for the specified target class Myproxyfactory{public static object GetProxy (object target) {MyInvocationhandler1 Hander1 = New MyInvocationhandler1 (); Hander1.settarget (target); return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), hander1);}} The dynamic proxy object implements the same interface as the target, class Testaop{public static void Main (string[] args) {Dog target = new Gundog ();D og Dog = (Dog) mypro Xyfactory.getproxy (target);d og.info ();d og.run ();}} /* * 4. Use reflection to get generic information */class generictest{//private Integer score;private map<string,integer> score;public Static void Main (string[] args) throws Nosuchfieldexception, securityexception{class<generictest> clazz = Generictest.class; Field f = Clazz.getdeclaredfield ("score"); Class<?> a = F.gettype (); System.out.println ("The type of score is:" +a); Type Gtype = F.getgenerictype (); if (Gtypeinstanceof Parameterizedtype) {parameterizedtype pt = (parameterizedtype) gtype; Type Rtype = Pt.getrawtype (); System.out.println ("Original type is:" +rtype);  type[] Targs = pt.getactualtypearguments (); Get the generic type SYSTEM.OUT.PRINTLN ("Generic information is:"), for (int i=0; i<targs.length; i++) {System.out.println ("+ (i+1) +" generic type is: " +targs[i]);}} ELSE{SYSTEM.OUT.PRINTLN ("Get Generic Information Error");}} }



to recognize the generic of a set from the reflection of a function

Import Java.lang.reflect.method;import Java.util.arraylist;import Java.util.list;public class ClassDemo4{public static void Main (string[] args) {List list1 = new ArrayList (); list<string> list2 = new arraylist<string> () List2.add ("QQQ");//list2.add (20); Compile Error Class C1 = List1.getclass (); Class C2 = List2.getclass (); SYSTEM.OUT.PRINTLN (C1 = = C2);/* The reflected operation is a compiled operation * C1==C2 The result is true, stating that the list collection after compilation is de-generics the Java collection of generics is to prevent erroneous input, only valid during the compilation phase, Bypass compilation is not valid *      Validation: Bypass compilation by the method's reflection operation */try{//method method = C2.getmethod ("Add", New Class[]{string.class}); method = C2.getmethod ("Add", object.class); Object obj = Method.invoke (list2,3); System.out.println (List2.size ());//print out the size of the List2 () is 2, which means that the integer 2 is added to the list2 with the string generic, the}catch (Exception e) { E.printstacktrace ();}}}


This section is the basis for Learning Java Framework knowledge and requires proficiency.

The foundation that Java developers must understand--reflection and dynamic proxy

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.