package poxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Simple Dynamic Proxy, show a single interface - a single instance case.
*
* @author daniel zhou
*/
public class SimpleDynamicProxy {
/**
* @param args
*/
public static void main(String[] args) {
//generate a hanlder
ProxyHanlder hanlder=new ProxyHanlder();
/*
* register instance to hanlder, get the interface's proxy
*/
Dog dogProxy=(Dog) hanlder.generateProxyHanlder(new Dog(){
@Override
public String eat(String food) {
return "Daniel's dog just ate an "+ food +"!";
}
});
//do method by proxy
String result = dogProxy.eat("big bone");
//take a look
System.out.println(result);
}
}
//Proxy Handler
class ProxyHanlder implements InvocationHandler{
//container
Object obj = new Object();
public Object generateProxyHanlder(Object obj) {
//store it
this.obj = obj;
//return interface proxy
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result=null;
result=method.invoke(obj, args);
return result;
}
}
//interface
interface Dog{
String eat(String food);
}
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* Simple Dynamic Proxy, show a single interface - a single instance case.
*
* @author daniel zhou
*/
public class SimpleDynamicProxy {
/**
* @param args
*/
public static void main(String[] args) {
//generate a hanlder
ProxyHanlder hanlder=new ProxyHanlder();
/*
* register instance to hanlder, get the interface's proxy
*/
Dog dogProxy=(Dog) hanlder.generateProxyHanlder(new Dog(){
@Override
public String eat(String food) {
return "Daniel's dog just ate an "+ food +"!";
}
});
//do method by proxy
String result = dogProxy.eat("big bone");
//take a look
System.out.println(result);
}
}
//Proxy Handler
class ProxyHanlder implements InvocationHandler{
//container
Object obj = new Object();
public Object generateProxyHanlder(Object obj) {
//store it
this.obj = obj;
//return interface proxy
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
obj.getClass().getInterfaces(),
this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result=null;
result=method.invoke(obj, args);
return result;
}
}
//interface
interface Dog{
String eat(String food);
}
转载于:https://blog.51cto.com/danni505/217359