<pre name="code" class="java">import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
interface A{
public void hello();
}
class B implements A{
public void hello(){
System.out.println("********hello!这是B********");
}
}
class B1 implements A{
public void hello(){
System.out.println("********hello!这是B1*******");
}
}
class C implements InvocationHandler{
Object proxyed=null;
C(Object proxy){
this.proxyed=proxy;
}
public Object invoke(Object proxy,Method m,Object[] args) throws Throwable{
Object result=null;
System.out.println("可以在调用具体的实现类方法前做一些其他事");
result=m.invoke(proxyed, args);
System.out.println("可以在调用具体的实现类方法后做一些其他事");
return result;
}
}
public class DynamicProxy {
public static void main(String[] args) {
B b=new B();
A a=(A) Proxy.newProxyInstance(b.getClass().getClassLoader(),
b.getClass().getInterfaces(), new C(new B()));
a.hello();
System.out.println("");
A a1=(A) Proxy.newProxyInstance(b.getClass().getClassLoader(),
b.getClass().getInterfaces(), new C(new B1()));
a1.hello();
}
}
java动态代理
最新推荐文章于 2024-04-17 16:08:00 发布