您的位置:首页 > 编程语言 > Java开发

Java反射机制学习3

2016-10-25 22:53 267 查看

代理

静态代理方法

interface ClothFactory{
void productCloth();
}

class NikeClothFactory implements ClothFactory{

@Override
public void productCloth() {
System.out.println("Nike Factory product clothes.");
}
}

class ProxyFactory implements ClothFactory{

ClothFactory cf;
public ProxyFactory(ClothFactory cf){
this.cf=cf;
}
@Override
public void productCloth() {
System.out.println("代理类执行.");
cf.productCloth();
}
}

public class TestClothProduct {
public static void main(String[] args){
NikeClothFactory ncf=new NikeClothFactory();
ProxyFactory proxy=new ProxyFactory(ncf);
proxy.productCloth();
}
}


运行结果

代理类执行.

Nike Factory product clothes.

动态代理

客户通过代理类来调用其它对象的方法并且是在程序运行时根据需要动态创建目标类的代理对象

interface Subject{
void action();
}

class RealSubject implements Subject{

@Override
public void action() {
System.out.println("被代理类调用action方法。。");
}
}

class MyInvocationHandler implements InvocationHandler{

private Object obj;

public Object blind(Object object){
this.obj=object;
return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("invoke()...start");
Object returnVal=method.invoke(obj,args);
System.out.println("invoke()...end");
return returnVal;
}
}
public class TestProxy {

public static void main(String[] args){
//被代理类的对象
RealSubject realSubject=new RealSubject();
MyInvocationHandler myInvocationHandler=new MyInvocationHandler();
Subject subject= (Subject) myInvocationHandler.blind(realSubject);
subject.action();
}
}


运行结果:

invoke()…start

被代理类调用action方法。。

invoke()…end

-

使用同态代理创建被代理对象(subject)后,该对象每次调用其所有方法,如上 subject.action()时会调用MyInvocationHandler 的invoke( )方法 。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java