背景
- 记录动态代理的使用过程
- 理解动态代理做了一件什么事情
过程
public interface InterfacePlugin {
void test(String name);
}
public class Plugin implements InvocationHandler {
private InterfacePlugin interfacePlugin = new InterfacePluginImpl();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("调用了接口InvocationHandler的实现类Plugin");
if (method.getName().equals("test")) {
System.out.println("执行类Plugin的业务逻辑过程:name=" + args[0]);
}
Object invoke = method.invoke(interfacePlugin, "impl");
return null;
}
}
public class InterfacePluginImpl implements InterfacePlugin{
@Override
public void test(String name) {
System.out.println("InterfacePluginImpl: " + name);
}
}
public class ProxyTest {
public static void main(String[] args) {
InterfacePlugin interfacePlugin = (InterfacePlugin)Proxy.newProxyInstance(
ProxyTest.class.getClassLoader(),
new Class[]{InterfacePlugin.class},
new Plugin());
interfacePlugin.test("life");
}
}
- 测试打印结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/1cc71bcdef472ee7951ebe153e1ba99c.png)
- 其他细节
- 添加了一个接口的实现类。Plugin类组合了这个实现类。这一部分跟动态代理没有任何关系,反射方法调用。
小结
- 动态代理,Java标准库提供了一种动态代理功能:可以在运行期动态创建接口interface的实例
- 动态代理,真正的业务逻辑处理过程其实是InvocationHandler的invoke方法
- 动态代理, jvm底层其实就是通过反射拿到接口的元信息,然后自己根据元信息生成class类,而这个class类就包含了开发者的所有业务逻辑过程。
- 动态代理,就是把接口进行了实例化,能够通过实例调用方法。底层就是生成了对应功能的一个类。