Java foundation agent


Create proxy object

To create a Proxy object, you need to use the newProxyInstance method of the Proxy class. This method has three parameters:
1. A classloader, as part of the Java security model, can be used for system classes and classes downloaded from the Internet
Different classloaders.
2. An array of Class objects. Each element is the interface to be implemented
3. A call handler.

Agents can be used for many reasons, such as:
1. Route method calls to the remote server.
2. Associate user interface events with actions during program operation.
3. Trace method calls for debugging.

public class ProxyTest {
    public static void main(String[] args) {
        Object[] elements = new Object[1000];
        for (int i = 0; i < elements.length; i++) {
            Integer value = i + 1;
            TraceHandler traceHandler = new TraceHandler(value);
            Object proxy = Proxy.newProxyInstance(null, new Class[]{Comparable.class}, traceHandler);
            elements[i] = proxy;

            Integer key = new Random().nextInt(elements.length) - 1;
            int result = Arrays.binarySearch(elements, key);
            if (result >= 0) {

class TraceHandler implements InvocationHandler {
    private Object target;

    public TraceHandler(Object target) { = target;

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("." + method.getName() + "(");
        if (args != null) {
            for (int i = 0; i < args.length; i++) {
                if (i < args.length - 1) {
        return method.invoke(target, args);

Properties of proxy class

The agent class is created during program execution. However, once created, it becomes a regular class, no different from any other class in the virtual machine.

All Proxy classes extend to Proxy classes. A Proxy class has only one instance domain - call handler. It is defined in the superclass of the Proxy.

Tags: Java

Posted on Fri, 01 May 2020 04:51:06 -0700 by timmytock