接口类:
public interface HelloService {
String sayHello(String name);
}
实现类:
public class HelloServiceImpl implements HelloService{
@Override
public String sayHello(String name) {
return "你好," + name;
}
}
代理工具类:
import java.lang.reflect.Proxy;
/**
* 动态代理工厂类,通过JDK动态代理创建代理对象
*/
public class ProxyFactory {
public static <T> T getProxy(Class<?> implClass) {
MyInvocationHandler invocationHandler = new MyInvocationHandler(implClass);
return (T) Proxy.newProxyInstance(implClass.getClassLoader(), implClass.getInterfaces(), invocationHandler);
}
}
处理器:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.List;
public class MyInvocationHandler implements InvocationHandler {
private Class<?> implClass;
public MyInvocationHandler(Class<?> implClass) {
this.implClass = implClass;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(implClass.newInstance(), args);
return result;
}
}
客户端:
public class Consumer {
public static void main(String[] args) {
System.out.println(" ===========[Consumer started!!]=============");
HelloService helloService = ProxyFactory.getProxy(HelloServiceImpl.class);
String result = helloService.sayHello("World");
System.out.println("Consumer.result:" + result);
}
}
标签:implClass,String,JDK,代理,class,result,动态,public,MyInvocationHandler
From: https://blog.51cto.com/u_11315052/8909638