日期:2011-04-13 09:24:00 来源:本站整理
<b>代理情势之Java动态代理</b>[Java编程]
本文“<b>代理情势之Java动态代理</b>[Java编程]”是由七道奇为您精心收集,来源于网络转载,文章版权归文章作者所有,本站不对其观点以及内容做任何评价,请读者自行判断,以下是其具体内容:
4.3 定义OwnerInvocationHandler类,表示假如为本人,则可以举行改正查看姓名性别.
Java代码
public class OwnerInvocationHandler implements InvocationHandler{
private Person personBean;
public OwnerInvocationHandler(Person personBean){
this.personBean = personBean;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws IllegalAccessException {
try {
if(method.getName().startsWith("get")){//假如办法名为get,就调用person类内的get呼应办法
return method.invoke(personBean, args);
}else if(method.getName().equals("setRate")){ // 假如办法是setRate,则抛出非常
throw new IllegalAccessException("access deny");
}else if(method.getName().startsWith("set")){ //假如为set,就调用person类内的set呼应办法
return method.invoke(personBean, args);
}else {
System.out.println("non method invoke");
}
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
}
4.4 定义NonInvocationHandler类,表示假如不为本人,则可以举行查看姓名性别和改正rate.
Java代码
public class NonInvocationHandler implements InvocationHandler{
//
private Person person;
public NonInvocationHandler(Person person){
this.person = person;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
if(method.getName().startsWith("setRate")){
return method.invoke(person, args);
}else if (method.getName().startsWith("get")){
return method.invoke(person, args);
} else {
System.out.println("non method invoke");
return null;
}
}
}
4.5 测试类MyDynamicProxy
Java代码
public class MyDynamicProxy {
public Person getOwnerPersonBeanProxy(Person person){
return (Person)Proxy.newProxyInstance(person.getClass().getClassLoader(),
person.getClass().getInterfaces(), new OwnerInvocationHandler(person));
}
public Person getNonPersonBeanProxy(Person person){
return (Person)Proxy.newProxyInstance(person.getClass().getClassLoader(),
person.getClass().getInterfaces(), new NonInvocationHandler(person));
}
public static void main(String[] args) {
MyDynamicProxy mdp = new MyDynamicProxy();
mdp.test();
}
public void test(){
//
Person person = getPersonBeanFromDB1();
Person personProxy = getOwnerPersonBeanProxy(person);
System.out.println(personProxy.getName());
try {
personProxy.setRate(2);
} catch (Exception e) {
System.out.println("can not setRate");
}
//
Person person1 = getPersonBeanFromDB1();
Person personProxy2 = getNonPersonBeanProxy(person1);
System.out.println(personProxy2.getName());
personProxy2.setRate(2);
System.out.println(personProxy2.getRate());
}
private Person getPersonBeanFromDB1(){
Person pb = new PersonImpl();
pb.setName("remy");
pb.setGender("girl");
pb.setRate(1);
return pb; }
输出后果:
Java代码
remy can not setRate remy 2
以上是“<b>代理情势之Java动态代理</b>[Java编程]”的内容,如果你对以上该文章内容感兴趣,你可以看看七道奇为您推荐以下文章:
本文地址: | 与您的QQ/BBS好友分享! |
评论内容只代表网友观点,与本站立场无关!
评论摘要(共 0 条,得分 0 分,平均 0 分)
查看完整评论