Home > Java > javaTutorial > body text

How to dynamically generate proxy classes in java

WBOY
Release: 2023-04-27 18:46:07
forward
1216 people have browsed it

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
Copy after login

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();
    }
}
Copy after login

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!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!