动态代理: 代理类需要实现InvocationHandler接口。
使用场合举例: 如果需要委托类处理某一业务,那么我们就可以先在代理类中,对客户的权限、各类信息先做判断,如果不满足某一特定条件,则将其拦截下来,不让其代理。
ServiceProxy.java
package com.ibm.dynamicproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ServiceProxy implements InvocationHandler {
private Object target;
public ServiceProxy(Object target){
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
result = method.invoke(target, args);
return result;
}
/**
* @param target
* @return 返回委托类接口的实例对象
*/
public Object getProxyInstance(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(),
target.getClass().getInterfaces(), this);
}
}
ServiceTest.java(测试类)
package com.ibm;
import com.ibm.delegate.Service;
import com.ibm.delegate.ServiceImpl;
import com.ibm.dynamicproxy.ServiceProxy;
public class ServiceTest {
流行线 /**
* @param args
*/
public static void main(String[] args) {
//创建委托类实例,即被代理的类对象
ServiceImpl target = new ServiceImpl();
//创建动态代理类
ServiceProxy proxy = new ServiceProxy(target);
Service service = (Service) proxy.getProxyInstance();
String date = service.queryDate();
System.out.println(date);
int result = service.sub(10, 20);
System.out.println("10-20 = "+result);
}
}
修改两个方法,做测试:
ServiceImpl.java
public String ownMethod(){
System.out.println("It's my own method");
return "user";
}
ServiceProxy.java
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = null;
if(!(target instanceof ServiceImpl)){
System.out.println("不能代理该对象");
return result;
}else if(!((ServiceImpl)target).ownMethod().equals("admin")){
System.out.println("权限不够");
return result;
}
result = method.invoke(target, args);
return result;
}
posted on 2012-06-27 15:36
墙头草 阅读(562)
评论(0) 编辑 收藏