Java Reflection and Proxy mode

Source: Internet
Author: User

Process Age:

Wash the dishes after dinner---"Wash your hands before meals----"

Dinner public interface Dinner {//meal method public void Havedinner ();}

  

Delegate class public class Mydinner implements Dinner {@Overridepublic void Havedinner () {System.out.println ("eat");}}

The proxy class implements the Invocationhandler interface

Import Java.lang.reflect.invocationhandler;import Java.lang.reflect.method;import java.lang.reflect.proxy;// The proxy class public class Mydinnerproxy implements Invocationhandler {Private Object originalobject;//the original object being proxied//binds to the proxy object, Returns a proxy object that is public object bind (object obj) {this.originalobject = obj;// returns: a proxy instance of the specified invocation handler with the proxy class, defined by the specified class loader. and implements the specified interface
Newproxyinstance parameters: Class loader, all interfaces assign call handlers for method calls to return Proxy.newproxyinstance (Obj.getclass (). getClassLoader (), Obj.getclass (). Getinterfaces (), this);} The method to be executed before eating private void Premethod () {System.out.println ("wash your hands before meals");} The method of executing after dinner private void Aftermethod () {System.out.println ("after Meal");} @Overridepublic object Invoke (Object proxy, Method method, object[] args) throws Throwable {Object result = Null;premethod ( ); result = Method.invoke (This.originalobject, args); System.out.println ("Rsult:" +result); Aftermethod (); return null;}}

  

public class Mydinnerproxydemo {public static void main (string[] args) {//1dinner dinner = new Mydinner ();d Inner.havedinne R ();//2mydinnerproxy proxy = new Mydinnerproxy ();//Returns a proxy object Dinner = (Dinner) proxy.bind (Dinner);// The method that executes the proxy object Dinner.havedinner ();}}

  

Proxyextends Objectimplements Serializable

ProxyProvides a static method for creating dynamic proxy classes and instances, or a superclass of all dynamic proxy classes created by these methods.

To create a Foo proxy for an interface:

     Invocationhandler handler = new Myinvocationhandler (...);     Class Proxyclass = Proxy.getproxyclass (         Foo.class.getClassLoader (), new class[] {foo.class});     Foo f = (foo) proxyclass.         GetConstructor (new class[] {invocationhandler.class}).         

or use the following simpler method:

     Foo f = (foo) proxy.newproxyinstance (Foo.class.getClassLoader (),                                          new class[] {foo.class},                                          handler);

  The Dynamic proxy class (hereinafter referred to as the proxy class ) is a class that implements a list of interfaces that are specified at run time when the class is created, and that class has the behavior described below. The Proxy interface is an interface implemented by the proxy class. The proxy instance is an instance of the proxy class. Each proxy instance has an associated call handler object that implements the interface InvocationHandler . a method call on a proxy instance through one of the proxy interfaces will be assigned to the Invoke method of the instance's call handler, passing the proxy instance, identifying the object calling the method, java.lang.reflect.Method and Object An array of types that contain the arguments. The calling handler handles the encoded method call in an appropriate manner, and the result it returns is returned as the result of the method call on the proxy instance.

The proxy class has the following properties:

  • The proxy class is public, final, and not abstract.
  • The unqualified name of the proxy class was not specified. However, "$Proxy" the class name space beginning with a string should be reserved for the proxy class.
  • proxy class extension java.lang.reflect.Proxy .
  • The proxy class accurately implements the interface specified when it was created, in the same order.
  • If the proxy class implements a non-public interface, it is defined in the same package as the interface. Otherwise, the package for the proxy class is not specified. Note that package sealing will not block the successful definition of the proxy class at run time in a particular package, nor will it block classes defined by the same classloader and packages with a specific signature.
  • Because the proxy class will implement all interfaces specified at the time of its creation, calls to its Class object getInterfaces will return an array containing the same list of interfaces (in the order specified when it was created), and calls to its Class objects getMethods will return an object that includes all the methods in those interfaces. Method object, and the call getMethod will find some of the expected methods in the proxy interface.
  • If the Proxy.isProxyClass method passes the proxy class (either by the Proxy.getProxyClass returned class, or by the Proxy.newProxyInstance class of the returned object), the method returns True, otherwise false is returned.
  • The proxy class is the same as the java.security.ProtectionDomain system class loaded by the boot class loader (such as java.lang.Object ), because the code for the proxy class is generated by the trusted system code. This protection domain is typically granted java.security.AllPermission .
  • Each proxy class has a public construction method that can take one parameter (an InvocationHandler implementation of the interface) to set the invocation handler for the proxy instance. You do not have to use the reflection API to access public construction methods, and Proxy.newInstance you can create a proxy instance by calling the method (combining the invoked action with the Proxy.getProxyClass constructor that invokes the handler).

The proxy instance has the following properties:

    • Provides a proxy instance proxy and an interface implemented by its proxy class, and the Foo following expression returns true:
           proxy instanceof Foo
      And the following cast operations will succeed (without throwing them ClassCastException ):
           (Foo) proxy
    • Each proxy instance has an associated call handler that is passed into its constructor method. The static Proxy.getInvocationHandler method returns the call handler associated with the proxy instance passed as its argument.
    • An interface method call on the proxy instance is encoded according to the method's document description and assigned to the method that invokes the handler Invoke .
    • A call to a declared, or method on a proxy instance is encoded in the java.lang.Object hashCode equals toString same way as the encoding and assigning interface method calls, and is assigned to the method that invokes the handler invoke , as described above. The declared class of the object passed to invoke Method is java.lang.Object . The proxy class does not rewrite java.lang.Object other public methods from the inherited proxy instances, so these methods have the same invocation behavior java.lang.Object as they do for the instance.
Methods for repeating in multi-agent interfaces

When two or more interfaces of a proxy class contain a method with the same name and parameter signature, the interface order of the proxy class becomes very important. When a repeating method is called on a proxy instance, the object passed to the calling handler Method is not necessarily an object whose declaring class can be assigned from the reference type of the interface, which invokes the proxy method through the interface. This limitation exists because the corresponding method implementation in the generated proxy class cannot determine which interface it is calling through. Therefore, when a repeating method is called on a proxy instance, the object of the method in the first interface Method contains the method in the list of proxy classes for the interface (either directly or through a super interface), and the object is passed to the method that invokes the handler invoke , regardless of the reference type that the method invocation takes place.

If the proxy interface contains a method whose name and parameter signature are the same as, or the same method, the object that is java.lang.Object hashCode equals toString passed to the calling handler Method will make its declaring class when the proxy instance calls such a method java.lang.Object . In other words, a java.lang.Object public non-final method is theoretically preceded by all proxy interfaces in order to determine which Method object is passed to the calling handler.

Also note that when a repeating method is assigned to the calling handler, the invoke method can only throw a checked exception type, which can be assigned an exception type by using the clauses of the method in all proxy interfaces (which can be called by it) throws . If invoke a method throws a checked exception that is not assigned to any exception type declared by a method in a proxy interface (which can be called by it), the call on that proxy instance throws an unchecked UndeclaredThrowableException . This restriction indicates that not all of the invoke exception types returned by the call on the object passed to the method Method getExceptionTypes can be invoke successfully thrown by the method.

Java Reflection and Proxy mode

Related Article

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.