interface DemoInterface {
String hello(String msg);
}
class DemoImpl implements DemoInterface {
@Override
public String hello(String msg) {
System.out.println("msg = " + msg);
return "hello";
}
}
class DemoProxy implements InvocationHandler {
private DemoInterface service;
public DemoProxy(DemoInterface service) {
this.service = service;
}
@Override
public Object invoke(Object obj, Method method, Object[] args) throws Throwable {
System.out.println("调用方法前...");
Object returnValue = method.invoke(service, args);
System.out.println("调用方法后...");
return returnValue;
}
}
public class Solution {
public static void main(String[] args) {
DemoProxy proxy = new DemoProxy(new DemoImpl());
DemoInterface service = Proxy.newInstance(
DemoInterface.class.getClassLoader(),
new Class<?>[]{DemoInterface.class},
proxy
);
System.out.println(service.hello("呀哈喽!"));
}
}
JAVA动态代理的例子
最新推荐文章于 2024-05-21 19:15:40 发布