标签:oid 实现类 ble throwable 服务 todo imp test load
package test;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
//被代理类接口
interface Buy{
public String buyc();
}
//被代理类
class People1 implements Buy{
@Override
public String buyc() {
// TODO Auto-generated method stub
System.out.println("我要买一个飞机");
return "飞机买完了";
}
}
//代理工厂
class ProxyF{
//获取代理类
public static Object getProxyInstance(Object obj) {
//通过构造器将被代理类传值给InvocationHandler的实现类
InvocationHandler handler = new Invoca(obj);
return Proxy.newProxyInstance(
obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
handler);
}
}
//InvocationHandler实现类
class Invoca implements InvocationHandler{
Object obj; //被代理类
Invoca(Object obj){
this.obj = obj;
}
//代理类要做的事情
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// TODO Auto-generated method stub
System.out.println("开启服务");
Object robj = method.invoke(obj,args);
System.out.println("更新日志");
return robj;
}
}
public class Z010_动态代理 {
public static void main(String[] args) {
// TODO Auto-generated method stub
People1 p = new People1();
Buy buy = (Buy) ProxyF.getProxyInstance(p);
String s = buy.buyc();
}
}
标签:oid 实现类 ble throwable 服务 todo imp test load
原文地址:https://www.cnblogs.com/yizhixiang/p/13324433.html