Java proxy class Proxy usage

Agent (proxy)

Agents can use to create an implementation of a set of new classes given interface at runtime. This function can not be determined at compile time only we need to implement what is only necessary when using the interface.

When to use a proxy

Suppose you have a Class object representing the interface (there may only contain one interface), it's impossible to know the exact type at compile time. To construct a class implementations of these interfaces, it is necessary to use a method or a reflective newInstance identify the class constructor. However, an interface can not be instantiated, you need to define a new class when the program is running.

Acting classes can create new classes at runtime. Such a proxy class can implement the specified interface. In particular, it has the following methods:

  • All the required method specified interface
  • All methods Object class, e.g., toString, equals the like.

Creating a proxy object

To create a proxy object, use newProxyInstance methods of the Proxy class. This method takes three parameters:

  • A class loader (class loader).
  • A Class array of objects, each element needs to implement.
  • A call processor

There are two problems to be solved. How to define a processor? What can be done with the results of a proxy object? Of course, the answer to both questions depends on what you plan to use a proxy mechanism to solve the problem. such as

  • Routing method calls to the remote server
  • Debug, trace
  • log

Demo

We define a processor, for printing the call parameters

public class TraceHandler implements InvocationHandler {

    private Object target;

    public TraceHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        System.out.print(target);
        System.out.print("." + method.getName() + "(");

        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                System.out.print(args[i]);
                if (i<args.length - 1){
                    System.out.print(", ");
                }
            }
        }

        System.out.println(")");

        return method.invoke(target, args);
    }
}

Next, we use it to proxy Comparable interface and see how calls. Arrays of such a binary search method binarySearch

    @Test
    public void traceBinarySearch() {
        Object[] elements = new Object[1000];

        for (int i = 0; i < elements.length; i++) {
            Integer value = i + 1;
            InvocationHandler handler = new TraceHandler(value);
            Object proxy = Proxy.newProxyInstance(null, new Class[]{Comparable.class}, handler);
            elements[i] = proxy;
        }

        Integer key = new Random().nextInt(elements.length) + 1;

        int result = Arrays.binarySearch(elements, key);

        if (result > 0) {
            System.out.println(elements[result]);
        }
    }

Console print the results:

500.compareTo(94)
250.compareTo(94)
125.compareTo(94)
62.compareTo(94)
93.compareTo(94)
109.compareTo(94)
101.compareTo(94)
97.compareTo(94)
95.compareTo(94)
94.compareTo(94)
94.toString()
94

Characteristics proxy class

  • The proxy class is created during operation, creation and after completion of the same general class, virtual machine treated equally.
  • All proxy classes extend to the Proxy class. Only one instance of a proxy class field --- call processor, which is defined in the Proxy superclass.
  • No name defined proxy class, Sun virtual machine Proxy class will generate a class name that begins with the string $ Proxy.
  • For a particular class loader and a predetermined set of interfaces, the proxy can have only one class. That is, if the same class loader and an array of interfaces called twice newProxyInstance method, it can only get two objects of the same class. For example, class com.sun.proxy.$Proxy4can be used getProxyClassto obtain this class.
  • The proxy class must be public final of.
  • You can Proxy.isProxyClassdetect whether a particular object represents a proxy class Class.

Guess you like

Origin www.cnblogs.com/woshimrf/p/java-proxy.html