Jdk动态代理Demo

Jdk动态代理的被代理类必须实现接口
JDK动态代理的组成
1.被代理类的接口 A
2.被代理类 B
3.实现了InvocationHandler接口的处理逻辑类 C(此类可复用)
4.Proxy.newProxyInstance(ClassLoader loader, Class[] interfaces, InvocationHandler h) throws IllegalArgumentException方法生成的代理类,此代理类实现了被代理类的接口A和接口Proxy.

接口及其实现

public interface Action {
    public void move();
}
public class ActionImpl  implements Action{
    @Override
    public void move() {
        System.out.println("target doing move");
    }
}

接口及其实现

public interface Hello {
    public String sayHello();
}

public class HelloImpl  implements Hello{
    @Override
    public String sayHello() {
        System.out.println("hello world");
        return "hello";
    }
}

接口InvocationHandler实现类


public class InvocationHandlerAction implements InvocationHandler {
    Object target;
    public InvocationHandlerAction(Object target) {
        this.target=target;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println(proxy.getClass().getName());
        System.out.println("执行代理");
        return method.invoke(target,args);
    }
}

测试类

public class JdkProxyAction {
    public static void main(String[] args) throws Exception {
        Action targetAction = new ActionImpl();
        Action proxy = (Action) Proxy.newProxyInstance(targetAction.getClass().getClassLoader(), targetAction.getClass().getInterfaces(), new InvocationHandlerAction(targetAction));
 /*       Field[] fields=proxy.getClass().getDeclaredFields();
        Stream.of(fields).map(Field::getName).forEach(System.out::println);

        Method[] methods=proxy.getClass().getDeclaredMethods();
        Stream.of(methods).map(Method::getName).forEach(System.out::println);*/

        proxy.move();

        System.out.println("-------------");

        Hello hello = new HelloImpl();
        Hello hello1 = (Hello) Proxy.newProxyInstance(hello.getClass().getClassLoader(), hello.getClass().getInterfaces(), new InvocationHandlerAction(hello));
        String result = hello1.sayHello();
        System.out.println(result);
        //输出动态生成代理类的字节码文件
        byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{Action.class});
        FileOutputStream outputStream = new FileOutputStream(new File("/Users/admin/record/temp/$Proxy0.class"));
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}

生成的动态代理类代码

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

import com.org.proxy.Action;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.lang.reflect.UndeclaredThrowableException;

public final class $Proxy0 extends Proxy implements Action {
    private static Method m1;
    private static Method m3;
    private static Method m2;
    private static Method m0;

    public $Proxy0(InvocationHandler var1) throws  {
        super(var1);
    }

    public final boolean equals(Object var1) throws  {
        try {
            return (Boolean)super.h.invoke(this, m1, new Object[]{var1});
        } catch (RuntimeException | Error var3) {
            throw var3;
        } catch (Throwable var4) {
            throw new UndeclaredThrowableException(var4);
        }
    }

    public final void move() throws  {
        try {
            super.h.invoke(this, m3, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final String toString() throws  {
        try {
            return (String)super.h.invoke(this, m2, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    public final int hashCode() throws  {
        try {
            return (Integer)super.h.invoke(this, m0, (Object[])null);
        } catch (RuntimeException | Error var2) {
            throw var2;
        } catch (Throwable var3) {
            throw new UndeclaredThrowableException(var3);
        }
    }

    static {
        try {
            m1 = Class.forName("java.lang.Object").getMethod("equals", Class.forName("java.lang.Object"));
            m3 = Class.forName("com.org.proxy.Action").getMethod("move");
            m2 = Class.forName("java.lang.Object").getMethod("toString");
            m0 = Class.forName("java.lang.Object").getMethod("hashCode");
        } catch (NoSuchMethodException var2) {
            throw new NoSuchMethodError(var2.getMessage());
        } catch (ClassNotFoundException var3) {
            throw new NoClassDefFoundError(var3.getMessage());
        }
    }
}


cglib动态代理请看这篇文章

https://editor.csdn.net/md?articleId=105955915

你可能感兴趣的:(虚拟机,java)