java代理(二)--jdk动态代理

时间:2021-07-03 15:19:36

在本节,主要介绍动态代理中的jdk代理。

jdk代理是动态代理,由于在编码中,不知道实际代理目标,因此需要用到反射机制,动态创建及获取代理对象。

jdk代理适用于实现了接口的类的代理。

jdk代理中涉及两个重要的类InvocationHandler和Proxy:

InvocationHandler是需要被实现的,代理目标在此实现类中注入,代理需实现的逻辑在此实现类的invoke方法内编写;

Proxy是代理类,类似于工厂方法,内部的newProxyInstance方法返回代理类对象,该对象是Proxy的子类,同时实现了代理目标的接口。

jdk代理实例如下:

public class JdkProxyMain {

public static void main(String[] args) {
HelloService helloService = new HelloServiceImpl();
HelloServiceInvocationHandler handler = new HelloServiceInvocationHandler(helloService);

HelloService helloServiceProxy = handler.getProxy();
helloServiceProxy.hello("jdkProxy");

Class<?> cls = handler.getProxyClass();
System.out.println(cls);

}

interface HelloService {
void hello(String name);
}

static class HelloServiceImpl implements HelloService {
@Override
public void hello(String name) {
System.out.println("hello,"+name);
}
}

static class HelloServiceInvocationHandler implements InvocationHandler {
private HelloService source;
public HelloServiceInvocationHandler(HelloService source) {
this.source = source;
}

public HelloService getProxy(){
return (HelloService)Proxy.newProxyInstance(source.getClass().getClassLoader(),source.getClass().getInterfaces(),this);
}

public Class<?> getProxyClass(){
return Proxy.getProxyClass(source.getClass().getClassLoader(),source.getClass().getInterfaces());
}


@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("use jdk proxy");
Object result = method.invoke(source,args);
return result;
}
}
}