Java动态代理

给出Java动态代理的示例,直接贴《Java编程思想》里的代码了。

示例

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* DynamicProxyDemo
*/
public class DynamicProxyDemo {
public static void consumer(Interface iface) {
iface.doSomething();
iface.somethingElse("hahaha");
}
public static void main(String[] args) {
RealObject real = new RealObject();
consumer(real);
System.out.println('\n' + "-------------------------" + '\n');
Interface proxy = (Interface)Proxy.newProxyInstance(Interface.class.getClassLoader(), new Class[] {Interface.class}, new DynamicProxyHandler(real));
consumer(proxy);
}
}
interface Interface {
void doSomething();
void somethingElse(String arg);
}
class RealObject implements Interface {
public void doSomething() {
System.out.println("doSomething");
}
public void somethingElse(String arg) {
System.out.println("somethingElse " + arg);
}
}
class DynamicProxyHandler implements InvocationHandler {
private Object proxied;
public DynamicProxyHandler(Object proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("**** proxy: " + proxy.getClass() + ", method: " + method + ", args: " + args);
return method.invoke(proxied, args);
}
}

欢迎关注公众号: FullStackPlan 获取更多干货

Copyright © 2016 - 2017 LBD's Blog All Rights Reserved.

访客数 : | 访问量 :