Home > Java > javaTutorial > body text

Analysis of JDK dynamic proxy examples in java

WBOY
Release: 2023-04-30 13:16:13
forward
770 people have browsed it

1. Description

Java provides a dynamic proxy class Proxy. Proxy is not a class of what we call proxy objects, but provides a static method for creating proxy objects. Method (newProxyInstance) to obtain the proxy object.

2. Example

public class HelloWorld {
    public static void main(String[] args) {
        // 获取代理对象
        ProxyFactory factory = new ProxyFactory();
        
        SellTickets proxyObject = factory.getProxyObject();
        
        proxyObject.sell();
    }
}
 
// 卖票接口
interface SellTickets {
    void sell();
}
 
// 火车站,火车站具有卖票功能,所以需要实现SellTickets接口
class TrainStation implements SellTickets {
    @Override
    public void sell() {
        System.out.println("火车站卖票");
    }
}
 
// 代理工厂,用来创建代理对象
class ProxyFactory {
    private TrainStation station = new TrainStation();
 
    public SellTickets getProxyObject() {
        // 使用Proxy获取代理对象
 
        /**
         * newProxyInstance() 方法参数说明:
         *  ClassLoader loader: 类加载器,用于加载代理类,使用真实对象的类加载器即可
         *  Class<?>[] interfaces:真实对象所实现的接口,代理模式真实对象和代理对象实现相同的接口
         *  InvocationHandler h:代理对象的调用处理程序
         */
 
        SellTickets sellTickets = (SellTickets) Proxy.newProxyInstance(
                station.getClass().getClassLoader(),
                new InvocationHandler() {
                    /**
                     * InvocationHandle中invoke方法参数说明:
                     *  proxy:代理对象
                     *  method:对应于在代理对象上调用的方法的Method实例
                     *  args:代理对象调用接口方法是传递的实际参数
                     */
                    
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        System.out.println("代理点收取一些服务费用(JDK动态代理方法)");
                        
                        // 执行真实对象
                        Object result = method.invoke(station, args);
                        return result;
                    }
                });
        return sellTickets;
    }
}
Copy after login

The above is the detailed content of Analysis of JDK dynamic proxy examples 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!