Reflection and dynamic Proxy for Java

Source: Internet
Author: User

I. Overview of REFLECTIONS

The Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the object's methods are called the reflection mechanisms of the Java language.

To dissect a class, you must first obtain the bytecode file object for that class. The anatomy uses the method in class. So first get the object of class type for each bytecode file. Reflection is a Java object that maps the various components of a Java class into one of the following. For example: A class has: member variables, methods, construction methods, packages and so on, The reflection technique can be used to dissect a class and map each component to a single object.

Second, the use of reflection

  Directly on the code

ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method;Importjava.util.ArrayList; Public classReflectdemo {PrivateString name; intAge ; @Override PublicString toString () {return"reflectdemo{" + "name=" + name + ' \ ' + ", age=" + Age + '} '; }     Public Static voidMain (string[] args)throwsclassnotfoundexception, Nosuchmethodexception, Illegalaccessexception, InvocationTargetException, Instanti Ationexception, nosuchfieldexception {//Assigning values to an object's properties, both private and common, can be assignedReflectdemo Reflectdemo =NewReflectdemo (); Reflectdemo.setproperty (Reflectdemo,"Name", "Your uncle"); Reflectdemo.setproperty (Reflectdemo,"Age", 2222);        System.out.println (Reflectdemo); //gets the bytecode file for the specified classClass C = class.forname ("Com.bytech.cn.dao.domain.AdminPo"); //all public construction methods through bytecode filesConstructor[] Constructors =c.getconstructors ();  for(Constructor constructor:constructors) {System.out.println (Constructor); }        //get all the construction methods through the bytecode fileconstructor[] Constructors1 =c.getdeclaredconstructors (); //obtaining the method of non-parameter construction by byte-code fileConstructor Constructor2 =C.getconstructor ();        System.out.println (CONSTRUCTOR2); //1. Get the reflection to get the constructor method and use theClass C3 = Class.forName ("Com.bytech.cn.dao.domain.AdminPo"); //2. Get the Parameter builderConstructor Constructor4 = C.getconstructor (Integer.class, String.class, String.class); //get This objectObject obj = constructor4.newinstance (2222, "222", "222");        System.out.println (obj); //get the private constructor methodConstructor Constructor5 = C.getdeclaredconstructor (String.class, String.class); //Violent visitsConstructor5.setaccessible (true); //Creating ObjectsObject obj2 = constructor5.newinstance ("AA", "BB"); System.out.println ("==============");        System.out.println (OBJ2); //get member variables and assign values to member variablesField adminfiled = C3.getdeclaredfield ("AdminName"); Adminfiled.setaccessible (true); Adminfiled.set (obj,"Administrator Name"); System.out.println ("~~~~~~~~~~~~~~~~~~~~~");        System.out.println (obj); //all methods to access//Public Menthod Getmothod (String name,class<?> ... parmetertypes)//The first parameter represents the method name, and the second parameter represents the method's parameter class classMethod M1 = C.getmethod ("Methods name")); /*Public object Invoke (Object Obj,object ... args)*/M1.invoke (obj);//invoke the M1 method of the Obj objectSystem.out.println ("============"); Method m2= C.getmethod ("Method name", String.)class); M2.invoke (obj,"Hello"); System.out.println ("================="); Method M3= C.getmethod ("getString", String.class, Integer.class); Object objectstring= M3.invoke (obj, "Hello", 100); Method M4= C.getdeclaredmethod ("function")); M4.setaccessible (true);        M4.invoke (obj); //I give you a arraylist<integer> object, I want to add a string in this collection of data, how to do it * ///Solution Startarraylist<integer> array =NewArraylist<>(); Array.add (11); Class ArrayClass1=Array.getclass (); Method m= Arrayclass1.getmethod ("Add", Object.class); M.invoke (Array,Hello);        SYSTEM.OUT.PRINTLN (array); System.out.println (".............................................."); Class Arrayclass= Class.forName ("Java.util.ArrayList"); Constructor Constructor=Arrayclass.getconstructor (); Object Object=constructor.newinstance (); Method Methodarray= Arrayclass.getmethod ("Add", Object.class); Methodarray.invoke (Object,"Hello ni da Ye");        System.out.println (object); //Answer complete    }        Public voidSetProperty (Object obj,string filedname,object filedvalue)throwsnosuchfieldexception, illegalaccessexception {Class C=Obj.getclass (); Field field=C.getdeclaredfield (filedname); Field.setaccessible (true);        Field.set (Obj,filedvalue); }}

Third, the realization of a dynamic agent

 Public Interface Userdao {    void  Add ();     void Delete ();     void update ();     void select ();}
 Public classUserdaoimplImplementsUserdao {@Override Public voidAdd () {System.out.println ("Add Features"); } @Override Public voidDelete () {System.out.println ("Remove Features"); } @Override Public voidUpdate () {SYSTEM.OUT.PRINTLN ("Modify Features"); } @Override Public voidSelect () {System.out.println ("Query Function"); }}
ImportJava.lang.reflect.InvocationHandler;ImportJava.lang.reflect.Method; Public classMyinvocationhandlerImplementsInvocationhandler {PrivateObject Target;//target Object     PublicMyinvocationhandler (Object target) { This. target =Target; } @Override PublicObject Invoke (Object proxy, Method method, object[] args)throwsthrowable {System.out.println ("Permission Check"); Object result=Method.invoke (Target,args); System.out.println ("Logging"); returnResult//returns a proxy object    }}
ImportJava.lang.reflect.Proxy; Public classTestproxy { Public Static voidMain (string[] args) {Userdao ud=NewUserdaoimpl ();        Ud.add ();        Ud.delete ();        Ud.select ();        Ud.update (); System.out.println ("----------------"); //We're going to create a dynamic proxy class//there is a method in the proxy class to create a dynamic proxy object//Public static class<?> Getproxyclass (ClassLoader loader,class<?> .... interfaces) throws IllegalArgumentExceptionMyinvocationhandler handler =NewMyinvocationhandler (UD); Userdao Userdaoproxy=(Userdao) proxy.newproxyinstance (Ud.getclass (). getClassLoader (), Ud.getclass (). Getinterfaces (), handler);        Userdaoproxy.update ();        Userdaoproxy.select ();        Userdaoproxy.delete ();    Userdaoproxy.add (); }}

This enables a dynamic agent to be implemented.

Reflection and dynamic Proxy for Java

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.