A brief talk on Java reflection and proxy _java

Source: Internet
Author: User
Tags array length reflection throwable

Java reflection mechanism and dynamic proxy, making Java more powerful, the spring core concept of IOC, AOP is through the reflection mechanism and dynamic proxy implementation.

1 Java Reflection

Example:

User user = new user ();
User.settime5flag ("test");
 
Class<?> cls = Class.forName ("Com.test.User");
Interfaces must be public, whether or not they are used inside this class! Alternatively, use Cls.getdeclaredmethod (), or traverse to modify the Accessibility method method
= Cls.getmethod ("Gettime5flag");
String res1 = (string) method.invoke (user);
System.out.println (res1);
When it comes to basic types such as int, use the int.class! integer.class!=int.class! Method
= Cls.getmethod ("Settime5flag", string.class); 
Method.invoke (User, "Rollen");
method = Cls.getmethod ("Gettime5flag");
String res2 = (string) method.invoke (user);
System.out.println (Res2);

Get the complete package name and class name from an object:

User.getclass (). GetName ()//Full path class name
User.getclass (). Getsimplename ()//Name of class without package name

Get class:

Class.forName ("Com.test.User");
Com.test.User.class;
User.getclass ();
Instantiate an object by class
User user = (user) cls.newinstance ();//There must be a parameterless constructor
Get all constructors
Constructor<?> cons[]=cls.getconstructors (); Returns
cons[0].newinstance () in declared order ()//no display declaration, with default constructor
Gets all the interface that a class implements
class<?> intes[] = cls.getinterfaces ();
Get parent class
Cls.getsuperclass ();
Get modifiers
int mo = Cls.getmodifiers ();
int mo = Cons[0].getmodifiers ();
int mo = Method.getmodifiers ();
Modifier.tostring (MO);
Get method parameters
Method.getparametors ();
Cons[0].getparametors ();
Get method Parameter type
Method.getparametortypes ();
Cons[0].getparametortypes ();
Gets all the exception types thrown by the method declaration
Method.getexceptiontypes ();
Get all the properties of this class declaration
field[] field = Cls.getdeclaredfields (); including Private
field[0].getmodifiers ();
Field[0].gettype ();

Gets all the exposed properties of this class, including the parent class declaration, the interface Declaration, all public properties declared by this class

Cls.getfields ();

Sets the specified property to access the

Field.setaccessible (true);
Field.set (obj, ' ces ');
Field.get (obj);

* GetFields () differs from Getdeclaredfields (): GetFields () can only access fields declared as common in a class, private fields it cannot access, and access to public fields inherited from other classes; Getdeclaredfields () can access all fields in a class, regardless of public,private,protect, but cannot access fields inherited from other classes

* GetMethods () differs from Getdeclaredmethods (): GetMethods () can only access publicly-declared methods in a class, private methods that are inaccessible, and access to public methods inherited from other classes; Getdeclaredmethods ( Can access all the fields in the class, independent of Public,private,protect, and cannot access methods inherited from other classes

* GetConstructors () differs from getdeclaredconstructors (): GetConstructors () can only access constructors declared as public in the class; Getdeclaredconstructors () can access all constructors in a class, regardless of Public,private,protect

Retrieving and modifying the information of an array through reflection


Int[] temp={1,2,3,4,5};
class<?> demo = Temp.getclass (). Getcomponenttype ();
SYSTEM.OUT.PRINTLN ("Array type:" +demo.getname ());//int
System.out.println ("Array Length:" +array.getlength (temp));//5
System.out.println ("first element of the array:" +array.get (temp, 0));//1
Array.set (temp, 0, MB);
System.out.println ("The first element of the array after modification is:" +array.get (temp, 0));//100
Get array type
Cls.getcomponenttype ();
Determines whether the array type
Cls.isarray ();

2 Java Proxy

Proxy mode is a common Java design pattern, it is characterized by proxy class and delegate class have the same interface, Agent class is mainly responsible for the delegation class preprocessing messages, filtering messages, forwarding messages to the delegate class, and afterwards processing messages. There is usually an association between a proxy class and a delegate class, the object of a proxy class is associated with an object of a delegate class, and the object of the proxy class does not actually implement the service, but rather provides a specific service by invoking the methods associated with the object of the delegate class.

According to the agent's creation period, the proxy class can be divided into 2 kinds.

• Static proxy: Generated by the programmer or a specific tool to generate the source code, and then compile. Before the program runs, the. class file for the proxy class already exists.

• Dynamic Agent: When the program is running, the Java reflection mechanism generates bytecode dynamically.

2.1 Static Agents

Public interface Count {public 
  void Querycount ();
}
public class Countimpl implements Count {public
  void Querycount () { 
    System.out.println ("View account Method ...");
  }
//proxy class public class
Countproxy implements Count { 
  private countimpl Countimpl;  
  Public Countproxy (Countimpl countimpl) { 
    This.countimpl = Countimpl; 
  }  
  @Override public 
  void Querycount () { 
    System.out.println (before transaction processing);      
    Countimpl.querycount (); The method that invokes the delegate class;
    System.out.println ("after Transaction"); 
  }
} 
//test class public
class Testcount {public 
  static void Main (string[] args) { 
    Countimpl Countimpl = new Co Untimpl (); 
    Countproxy countproxy = new Countproxy (COUNTIMPL); 
    Countproxy.querycount ();  
  } 
}

The observation code can be found that each proxy class can only serve one interface, so the program development will inevitably generate too many agents, and all agent operations in addition to the method of invocation, all other operations are the same, then it must be repeated code. The best way to solve this problem is to use a proxy class to complete all the agent functions, and then you must do so using dynamic agents.

2.2 Dynamic Proxy

The byte code of the dynamic proxy class is generated dynamically by the Java reflection mechanism when the program is run, without the programmer writing its source code manually. Dynamic proxy classes Not only simplify programming, but also improve the scalability of software systems, because the Java reflection mechanism can generate any type of dynamic proxy class.

2.2.1 JDK Dynamic Proxy

The proxy class and the Invocationhandler interface in the Java.lang.reflect package provide the ability to generate dynamic proxy classes.

Invocationhandler Interface:

Public interface Invocationhandler {
public object Invoke (Object Proxy,method method,object[] args) throws Throwable;
}

Parameter description:

Object proxy: Refers to the objects being represented.
Methods: The method to invoke
object[] args: Parameters required for method invocation

The subclass of the Invocationhandler interface can be imagined as the final action class of an agent, replacing the proxysubject.

Proxy class:

A proxy class is an action class that specifically completes a proxy that enables you to dynamically build an implementation class for one or more interfaces, which provides the following methods of action:

public static Object newproxyinstance (ClassLoader loader, class<?>[] interfaces, Invocationhandler h) throws IllegalArgumentException

Parameter description:

ClassLoader Loader: Class loader
Class<?>[] Interfaces: Get all the interfaces
Invocationhandler h: A subclass instance that gets the Invocationhandler interface

If you want to complete a dynamic proxy, you first need to define a subclass of the Invocationhandler interface to complete the agent's actions.

Interface Subject {public string say (string name, int age);} class Realsubject implements Subject {@Override pub
  Lic string Say (string name, int age) {return name + ' "+ age;
  }//JDK Dynamic proxy class Myinvocationhandler implements Invocationhandler {private Object target = null;
    Binds the delegate object and returns a proxy class public object bind (object target) {this. target = target; Return Proxy.newproxyinstance (Target.getclass (). getClassLoader (), Target.getclass (). Getinterfaces (), this); 
    To bind the interface (Cglib make up for this)} @Override public Object invoke (Object Proxy, Method method, object[] args) throws Throwable {
    System.out.println ("before method!");
    Object temp = Method.invoke (target, args);
    System.out.println ("after method!");
  return temp;
    Class Hello {public static void main (string[] args) {Myinvocationhandler demo = new Myinvocationhandler ();
    Subject sub = (Subject) demo.bind (New Realsubject ());
    String info = Sub.say ("Rollen", 20); SystEM.OUT.PRINTLN (info); }
}

However, the dynamic proxy for JDK relies on the interface implementation, and if some classes do not implement the interface, the JDK proxy cannot be used, which requires the use of the Cglib dynamic proxy.

2.2.2 Cglib Dynamic Agent

The dynamic proxy mechanism of JDK can only broker the class that implements the interface, but the class without implementing the interface cannot implement the dynamic proxy of JDK.

Cglib implements proxies for classes by generating a subclass of the specified target class and overriding the method implementation enhancements, but because inheritance is used, the final-decorated class cannot be represented.

Public interface Bookfacade {public void Addbook (); 
  public class BookFacadeImpl1 {public void Addbook () {System.out.println ("general method to add Books ...");  
}} import Java.lang.reflect.Method; 
Import Net.sf.cglib.proxy.Enhancer; 
Import Net.sf.cglib.proxy.MethodInterceptor; 
Import Net.sf.cglib.proxy.MethodProxy;  
  Cglib Dynamic proxy class public class Bookfacadecglib implements Methodinterceptor {private Object target; 
    Binds the delegate object and returns a proxy class public object getinstance (object target) {this.target = target; 
    Enhancer enhancer = new enhancer (); 
    Enhancer.setsuperclass (This.target.getClass ()); 
    Callback method Enhancer.setcallback (this); 
  Create proxy object return Enhancer.create (); The @Override//callback method is public object intercept (object obj, algorithm method, object[] args, Methodproxy proxy) 
    Throws Throwable {System.out.println ("things Begin"); 
    Object temp = proxy.invokesuper (obj, args); 
    System.out.println ("The End of Things");  
  return temp; }} public Class Testcglib {public static void main (string[] args) {bookfacadecglib cglib = new Bookfacadecglib (); 
    BookFacadeImpl1 bookcglib = (BOOKFACADEIMPL1) cglib.getinstance (New BookFacadeImpl1 ()); 
  Bookcglib.addbook (); } 
}

The above is a brief discussion of the Java reflection and the agent is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.