import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class Test {
interface HelloWorld{
int sayHello();
}
class HelloWorldIpml implements HelloWorld{
@Override
public int sayHello() {
System.out.println("hello world");
return 1;
}
}
class ProxyFactory{
private Object target; //真是对象
ProxyFactory(Object target){
this.target=target;
}
public Object getProxyInstance() {
//代理对象
Object proxy=Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(),
new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("执行代理方法");
//反射调用真是对象的方法
Object result=method.invoke(target, args);
System.out.println(result);
return result;
}
});
return proxy;
}
}
public static void main(String[] args) {
Test aTest=new Test();
HelloWorld helloWorldIpml=aTest.new HelloWorldIpml();
HelloWorld proxy=(Test.HelloWorld)aTest.new ProxyFactory(helloWorldIpml).getProxyInstance();
proxy.sayHello();
}
}