jdk动态代理实现

时间:2023-03-09 05:20:15
jdk动态代理实现

1、jdk动态代理的简单实现类

package com.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy; public class JDKProxy implements InvocationHandler{ private Object target;//目标对象 public JDKProxy(Object target) {
super();
this.target = target;
} @Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("--------------------invoke-before----------------------");
Object object = method.invoke(target, args);
System.out.println("--------------------invoke-after----------------------");
return object;
} public Object getProxy(){
return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this);
} }

2、测试用接口和接口实现

package com.proxy.manager;

public interface HelloWorldManager {

    public void sayHello();

}
package com.proxy.manager.impl;

import com.proxy.manager.HelloWorldManager;

public class HelloWorldManagerImpl implements HelloWorldManager {

    @Override
public void sayHello() {
System.out.println("Hello World!");
} }

3、测试类

package com.proxy.test;

import com.proxy.JDKProxy;
import com.proxy.manager.HelloWorldManager;
import com.proxy.manager.impl.HelloWorldManagerImpl; public class JDKProxyTest { public static void main(String[] args) {
HelloWorldManager hw = new HelloWorldManagerImpl();
JDKProxy jdkProxy = new JDKProxy(hw);
HelloWorldManager hellWorldManager = (HelloWorldManager) jdkProxy.getProxy();
hellWorldManager.sayHello();
} }

4、测试输出接口

--------------------invoke-before----------------------
Hello World!
--------------------invoke-after----------------------