JAVA动态代理

动态代理是Java中一种强大的机制,可以在运行时创建代理类和对象。通过使用JDK动态代理,你可以实现在目标类的方法执行前后进行不同的增强操作。

首先,定义一个接口,该接口包含你想要代理的方法:

public interface MyInterface {
    void method1();
    String method2(String input);
}

然后,创建一个实现该接口的目标类:

public class MyTargetClass implements MyInterface {
    @Override
    public void method1() {
        System.out.println("Executing method1");
    }

    @Override
    public String method2(String input) {
        System.out.println("Executing method2 with input: " + input);
        return "Output from method2";
    }
}

接下来,创建一个实现InvocationHandler接口的类,用于定义代理对象的行为:

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

public class MyInvocationHandler implements InvocationHandler {
    private final Object target;

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 在方法执行前的增强操作
        System.out.println("Before executing method: " + method.getName());

        // 调用目标对象的方法
        Object result = method.invoke(target, args);

        // 在方法执行后的增强操作
        System.out.println("After executing method: " + method.getName());

        return result;
    }
}

最后,创建一个测试类,使用Proxy.newProxyInstance方法创建代理对象并调用方法:

import java.lang.reflect.Proxy;

public class ProxyExample {
    public static void main(String[] args) {
        // 创建目标对象
        MyInterface target = new MyTargetClass();

        // 创建InvocationHandler实例
        MyInvocationHandler handler = new MyInvocationHandler(target);

        // 创建代理对象
        MyInterface proxy = (MyInterface) Proxy.newProxyInstance(
                MyInterface.class.getClassLoader(),
                new Class[]{MyInterface.class},
                handler
        );

        // 调用代理对象的方法
        proxy.method1();
        String result = proxy.method2("Hello");
        System.out.println("Result from method2: " + result);
    }
}

在上述例子中,MyInvocationHandler类中的invoke方法定义了在方法执行前和执行后的增强操作。

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值