java动态代理

it2023-01-22  53

实例代码: 

public interface Me { public void sayHello(); } import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; class MyHandler implements InvocationHandler{ Object target; public MyHandler(Object target) { this.target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("start"); method.invoke(target,args); System.out.println("end"); return null; } } class MeImpl implements Me { @Override public void sayHello() { System.out.println("hello"); } } public class TestProxy { public static void main(String[] args) { MeImpl meImpl = new MeImpl(); MyHandler myHandler = new MyHandler(meImpl); Me me = (Me)Proxy.newProxyInstance(meImpl.getClass().getClassLoader(), meImpl.getClass().getInterfaces(), myHandler); me.sayHello(); } }

 

最新回复(0)