Java 注解、反射、代理 整理记录

1.注解:标签

2.反射:动态获取或者执行

3.代理:委托

1.动态代理

public class TestC implements TestP {
    @Override
    public String methodOne(String name) {
        return name + "method one";
    }

    @Override
    public void methodTwo() {

        System.out.println("method two");
    }
}
public class TestProxy {

    public static TestP createProxy(TestC testC) {

        TestP testP = (TestP)Proxy.newProxyInstance(testC.getClass().getClassLoader(), testC.getClass().getInterfaces(), new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

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

                return method.invoke(testC,args);
            }
        });

        return testP;
    }
}
public class Test2 {

    @Test
    void test() {

        TestC testC = new TestC();

        TestP testP = TestProxy.createProxy(testC);

        String c = testP.methodOne("boy");

        testP.methodTwo();

        System.out.println(c);
    }

}

2.cglib增强字节码:运行时创建目标类的子类,从而对目标类进行增强

public class TestEnhancer {

    public static TestC createEnhancer(TestC testC) {

        //创建增强对象
        Enhancer enhancer = new Enhancer();
        //设置父类
        enhancer.setSuperclass(TestC.class);
        //设置回调【拦截】
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

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

                //执行方法
//                Object object = method.invoke(testC,objects);
                //执行代理类的方法(目标类和代理类式父子关系)
                Object object = methodProxy.invokeSuper(o,objects);
                return object;
            }
        });
        TestC testC1 = (TestC)enhancer.create();

        return testC1;
    }
}

你可能感兴趣的:(Java 注解、反射、代理 整理记录)