public interface Foo {
void doAction();
}
//*********************************
package com.ygl.dynamicproxy;
public class FooImpl implements Foo{
public void doAction() {
System.out.println("doAction FooImpl");
};
}
//*********************************
package com.ygl.dynamicproxy;
public class FooImpl2 implements Foo{
public void doAction() {
System.out.println("doAction FooImpl2");
};
}
//************************************
package com.ygl.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class CommonInvocationHandler implements InvocationHandler {
private Object target;
public CommonInvocationHandler(Object target){
this.target=target;
}
public CommonInvocationHandler(){
}
public Object getTarget() {
return target;
}
public void setTarget(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
return method.invoke(target, args);
}
public static void main(String[] args) {
CommonInvocationHandler commonInvocationHandler=new CommonInvocationHandler();
Foo fooProxy=null;
commonInvocationHandler.setTarget(new FooImpl());
fooProxy= (Foo)Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[]{Foo.class},commonInvocationHandler);
fooProxy.doAction();
}
}