java

位置:IT落伍者 >> java >> 浏览文章

java动态代理Dynamic Proxy


发布日期:2022年08月29日
 
java动态代理Dynamic Proxy

被代理对象的接口:

package testdynamicproxy;

public interface TargetInterface {

public void SayHello();

public int sum(int a int b);

}

被代理的对象:

package testdynamicproxy;

public class Target implements TargetInterface {

public void SayHello(){

Systemoutprintln(Hello);

}

public int sum(int a int b) {

return a+b;

}

}

InvocationHandler包装:

package testdynamicproxy;

import javalangreflectInvocationHandler;

import javalangreflectMethod;

public class TargetInvocationHandler implements InvocationHandler {

private Object object;

public TargetInvocationHandler(Object obj){

thisobject=obj;

}

public Object invoke(Object proxy Method method Object[] args)

throws Throwable

{

doBefore();

Object result = methodinvoke(object args);

doAfter();

return result;

}

public void doBefore(){

Systemoutprintln(do before);

}

public void doAfter(){

Systemoutprintln(do after);

}

}

测试类:

package testdynamicproxy;

import javalangreflectProxy;

public class TestDynamicProxy {

/**

* @param args

*/

public static void main(String[] args) {

Target t=new Target();

TargetInvocationHandler handler=new TargetInvocationHandler(t);

TargetInterface proxy = (TargetInterface) ProxynewProxyInstance(

tgetClass()getClassLoader()

tgetClass()getInterfaces()

handler);

proxySayHello();

int b=proxysum( );

Systemoutprintln(b);

}

}

               

上一篇:用shell和java实现自动部署

下一篇:提高Java代码可重用性的措施