SmsService
package org.example;
public interface SmsService {
String send(String message);
}
SmsServiceImpl
package org.example;
public class SmsServiceImpl implements SmsService {
@Override
public String send(String message) {
System.out.println("发送信息" + message);
return "已经发送信息: " + message;
}
}
DynamicInvocationHandler —> 实际得代理类
package org.example;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class DynamicInvocationHandler implements InvocationHandler {
private final Object target;
public DynamicInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("before method " + method.getName());
Object result = method.invoke(target, args);
System.out.println("after method " + method.getName());
return result;
}
}
ProxyFactory
package org.example;
import java.lang.reflect.Proxy;
public class ProxyFactory {
public static Object getProxy(Object target) {
return Proxy.newProxyInstance(
target.getClass().getClassLoader(), // 目标类的类加载器
target.getClass().getInterfaces(), // 代理需要实现的接口,可指定多个
new DynamicInvocationHandler(target) // 代理对象对应的自定义 InvocationHandler
);
}
}
Main
package org.example;
public class Main {
public static void main(String[] args) {
SmsService smsService = (SmsService) ProxyFactory.getProxy(new SmsServiceImpl());
smsService.send("hello");
}
}