InvocationHandler
Java 代理,InvocationHandler,Proxy
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
Test t=new Test();
t.inter();
}
void inter(){
ServiceProxy proxy = new ServiceProxy();
ServiceImpl service = new ServiceImpl();
proxy.setService(service);
Object service2 = Proxy.newProxyInstance(ServiceImpl.class.getClassLoader(), new Class[]{Service.class}
, proxy);
System.out.println(service2.getClass());
Service s = (Service)service2; //只能转换为接口
}
}
interface Service{
String prt();
}
class ServiceImpl implements Service{
public String prt(){
System.out.println(" Interface Impl");
return "InterFaceImpl";
}
}
class ServiceProxy implements InvocationHandler{
Object service;
void setService(Object service){
this.service=service;
}
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object o=null;
o=method.invoke(service, args);
return o;
}
}