java动态代理简单实例
package hello;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface AbstractClass {
public void show();
}
class ClassA implements AbstractClass {
public void show() {
System.out.println("我是A类");
}
}
// 具体类B
class ClassB implements AbstractClass {
public void show() {
// TODO Auto-generated method stub
System.out.println("我是B类!");
}
}
class Invoker implements InvocationHandler {
AbstractClass ac;
public Invoker(AbstractClass ac) {
this.ac = ac;
}
public Object invoke(Object proxy, Method method, Object[] arg) throws Throwable {
method.invoke(ac, arg);
return null;
}
}
// test
class HelloWorld {
public static void main(String[] args) {
Invoker invoker1 = new Invoker(new ClassA());
AbstractClass ac1 = (AbstractClass) Proxy.newProxyInstance(AbstractClass.class.getClassLoader(), new Class[]{AbstractClass.class},invoker1);
ac1.show();
Invoker invoker2 = new Invoker(new ClassA());
AbstractClass ac2 = (AbstractClass) Proxy.newProxyInstance(AbstractClass.class.getClassLoader(), new Class[]{AbstractClass.class},invoker2);
ac2.show();
}
}
执行结果是:
- 我是A类!
- 我是B类!