在Java中,可以使用java.lang.reflect.Proxy
类来创建代理对象。以下是创建代理对象的步骤:
public interface MyInterface {
void doSomething();
}
public class MyInterfaceImpl implements MyInterface {
@Override
public void doSomething() {
System.out.println("MyInterfaceImpl: doSomething");
}
}
java.lang.reflect.InvocationHandler
接口的类。这个类将处理代理对象上的方法调用。import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class MyInvocationHandler implements InvocationHandler {
private Object target;
public MyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("Before method call");
Object result = method.invoke(target, args);
System.out.println("After method call");
return result;
}
}
Proxy.newProxyInstance()
方法创建代理对象。import java.lang.reflect.Proxy;
public class Main {
public static void main(String[] args) {
MyInterfaceImpl realObject = new MyInterfaceImpl();
MyInvocationHandler handler = new MyInvocationHandler(realObject);
MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class[]{MyInterface.class},
handler);
proxy.doSomething();
}
}
运行上述代码,将看到以下输出:
Before method call
MyInterfaceImpl: doSomething
After method call
这表明代理对象在调用doSomething()
方法之前和之后执行了额外的操作。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。