Java动态代理使用

来源:互联网 发布:知乎融资 编辑:程序博客网 时间:2024/05/22 05:19



//代理处理类

public class ServiceProxyHandler implements InvocationHandler{
private Object target = null;

public ServiceProxyHandler(Object target) {
this.target = target;


@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
Object result = method.invoke(target, args);
return result;
}
}


//接口
public interface MyInterface{
public void process();
}


//实现类

public class MyImpl implements MyInterface{


@Override
public void process() {
System.out.println("processing...");
}
}


//测试类

public class Test {

public static void main(String[] args) {
MyImpl impl = new MyImpl();//目标类
MyInterface mf = (MyInterface) Proxy.newProxyInstance(impl.getClass().getClassLoader(), impl.getClass().getInterfaces(), new ServiceProxyHandler(impl));
mf.process();
}

}






原创粉丝点击