小弟菜鸟,刚看动态代理,想请教诸位牛人一个问题,就是如何在InvocationHandler中代理多个方法?
比如有个接口叫Test,代码如下
[code="java"]public interface Test
{
void methodA();
void methodB();
void methodC(String a);
}[/code]
现在我有个实现类叫TestImpl,代码如下
[code="java"]
public class TestImpl implements Test
{
public void methodA()
{
Syste.out.println("methodA is invoked");
};
public void methodB()
{
Syste.out.println("methodBis invoked");
};
public void methodC(String s)
{
Syste.out.println("methodC receive parameter "+s);
};
}
[/code]
现在我希望有个TestImplProxy,它的作用是当调用TestImpl类中的MethodsA方法时,能够在[color=red]方法methodA运行前[/color]打印“I will run methodA”,能够在[color=red]方法methodB运行后[/color]打印“I have finished methodB”,能够在[color=red]方法methodC运行前[/color]打印“I will run methodC”和[color=red]运行后[/color]打印“I have finished methodC”
恳请熟悉的朋友能写个实例代码,谢谢您了
Java动态代理的疑问
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- wanghaolovezlq 2009-04-14 12:03关注
[code="java"]
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;public class DynamicProxyTest {
/** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Test test = new TestImpl(); InvocationHandler handler = new TestHandler(test); Object proxy = Proxy.newProxyInstance(test.getClass().getClassLoader(), test.getClass().getInterfaces(), handler); Test proxyAfter = (Test)proxy; proxyAfter.methodA(); proxyAfter.methodB(); proxyAfter.methodC("aa"); }
}
class TestHandler implements InvocationHandler
{
/**
Constructs a TraceHandler
@param t the implicit parameter of the method call
*/
public TestHandler(Object t)
{
target = t;
}public Object invoke(Object proxy, Method m, Object[] args) throws Throwable
{
if(m.getName().equals("methodA"))
{
System.out.println("I will run methodA");
return m.invoke(target, args);
}
else if(m.getName().equals("methodB"))
{
System.out.println("I have finished methodB");
return m.invoke(target, args);
}
else if(m.getName().equals("methodC"))
{
System.out.println("I will run methodC");
Object o = m.invoke(target, args);
System.out.println("I have finished methodC");
return o;
}return m.invoke(target, args);
}
private Object target;
}interface Test
{
void methodA();
void methodB();
void methodC(String a);
}class TestImpl implements Test
{
public void methodA()
{
System.out.println("methodA is invoked");
};
public void methodB()
{
System.out.println("methodBis invoked");
};
public void methodC(String s)
{
System.out.println("methodC receive parameter "+s);
};
}[/code]
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
- ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
- ¥16 mybatis的代理对象无法通过@Autowired装填
- ¥15 可见光定位matlab仿真
- ¥15 arduino 四自由度机械臂
- ¥15 wordpress 产品图片 GIF 没法显示
- ¥15 求三国群英传pl国战时间的修改方法
- ¥15 matlab代码代写,需写出详细代码,代价私
- ¥15 ROS系统搭建请教(跨境电商用途)
- ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。