import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
// 定义一个接口
interface MyInterface {
int doSomething();
String doSomething2();
}
// 实现 InvocationHandler 接口,用于处理方法调用
class MyInvocationHandler implements InvocationHandler {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 在这里编写自定义的实现逻辑
System.out.println("Do something in the implementation class.");
if (method.getName().equals("doSomething")) {
return 123;
} else {
return "456";
}
}
}
public class Main {
public static void main(String[] args) {
// 创建代理对象
MyInterface myInterface = (MyInterface) Proxy.newProxyInstance(
MyInterface.class.getClassLoader(),
new Class[] { MyInterface.class },
new MyInvocationHandler());
// 调用代理对象的方法
int r = myInterface.doSomething();
String r1 = myInterface.doSomething2();
System.out.println(r);
System.out.println(r1);
}
}
来自chatgpt。