JDK动态代理例子

JDK动态代理的代理类必须实现于接口。如果要代理类,则使用CGLIB代理。

先定义一个接口:

public interface Character {
    public void show();
}

接着定义一个类:

public class A implements Character{

    @Override
    public void show() {
        // TODO Auto-generated method stub
        System.out.println("this is A");
    }
    
}

定义的代理类要实现InvocationHandler接口:

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;


public class JdkProxy implements InvocationHandler{
    private Object delegate;
    public Object bind(Object delegate){
        this.delegate = delegate;
     //利用反射机制生成一个代理对象
return Proxy.newProxyInstance(delegate.getClass().getClassLoader(), delegate.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub Object result = null;
      System.out.println(
"JdkProxy invoke");
     //此处是调用了目标类的方法,所以在该方法执行的前后可以插入其他的事务逻辑,并且可以更改传入的参数和返回的结果 result
= method.invoke(delegate, args); return result; } }

例子:

public static void main(String[] args){
        Character c = (Character)((new JdkProxy()).bind(new A()));
        c.show();
    }

打印的结果:

JdkProxy invoke
this is A
原文地址:https://www.cnblogs.com/agindage/p/4684377.html