package tmp;
import java.lang.reflect.Field; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Modifier; import java.lang.reflect.Method;
public class test {
public interface Hello { void morning(String name); } public static class HelloWorld implements Hello { public void morning(String name) { System.out.println("Good morning, " + name); } } public static void main(String[] args) throws Exception{ InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(method); if (method.getName().equals("morning")) { System.out.println("Good morning, " + args[0]); System.out.println("proxy.getClass().getName()"); } return null; } }; Hello hello = (Hello) java.lang.reflect.Proxy.newProxyInstance( Hello.class.getClassLoader(), new Class[]{Hello.class}, handler); hello.morning("Bob"); } }
|
实际是是JVM在运行的时候创建的class字节码并加载
public class HelloDynamicProxy implements Hello { InvocationHandler handler; public HelloDynamicProxy(InvocationHandler handler) { this.handler = handler; } public void morning(String name) { handler.invoke( this, Hello.class.getMethod("morning", String.class), new Object[] { name }); } }
|