Home  >  Article  >  Java  >  How to dynamically generate proxy classes in java

How to dynamically generate proxy classes in java

WBOY
WBOYforward
2023-04-27 18:46:071171browse

Instructions

1. Call the newProxyInstance method of the Proxy class to obtain the proxy class instance.

2. This proxy class implements the specified interface and distributes method calls to the specified call processor.

Method declaration

public static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h) throws IllegalArgumentException

Parameters

loader: ClassLoder that defines the proxy class

interfaces: List of interfaces implemented by the proxy class

h: Invocation processor, which is the class instance we defined above that implements the InvocationHandler interface

Instance

public class Main {
    public static void main(String[] args) {
        //创建中介类实例
        DynamicProxy inter = new DynamicProxy(new Vendor());
        //加上这句将会产生一个$Proxy0.class文件,这个文件即为动态生成的代理类文件
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
 
        //获取代理类实例sell
        Sell sell = (Sell)(Proxy.newProxyInstance(Sell.class.getClassLoader(), new Class[] {Sell.class}, inter));
 
        //通过代理类对象调用代理类方法,实际上会转到invoke方法调用
        sell.sell();
        sell.ad();
    }
}

The above is the detailed content of How to dynamically generate proxy classes in java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete