小弟菜鸟,刚看动态代理,想请教诸位牛人一个问题,就是如何在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”
恳请熟悉的朋友能写个实例代码,谢谢您了
[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]
楼上正解。。。