jdk动态代理实践

jdk动态代理编写步骤

a)定义Subject接口,定义Subject接口实现类RealSubject
b)添加InvocationHandler接口实现类InvocationHandlerImpl,内部持有RealSubject对象,重写invoke方法,添加前置,后置逻辑
c)使用:使用Proxy.newProxyInstance()方法生成Subject接口的代理对象,需要传入类加载器、被代理类的所有接口,调用处理器(classLoader、interfaces、handler)
d)代理类调用方法,代理成功

接口类Subject

public interface Subject{
	String hello(String name);
}

接口类Subject实现类RealSubject

public class RealSubject implements Subject{
	@Override
	public String hello(String name){
		System.out.println("hello...");
		return "hello "+name;
	}
}

InvocationHandler实现类InvocationHandlerImpl

public class InvocationHandlerImpl implements InvocationHandler{
	// 持有被代理类
	private Object subject;
	public InvocationHandlerImpl(Object subject){
		this.subject = subject;
	}
	@Override
	public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
		System.out.println("begin invoke ...");
		Object returnValue = method.invoke(subject,args);
		System.out.println("end invoke ...");
		return returnValue;
	}
}

jdk动态代理使用

public static void main(String[] args){
	// 被代理类
	RealSubject realSubject = new RealSubject();
	// 调用处理类(aop部分)
    InvocationHandlerImpl handler = new InvocationHandlerImpl(realSubject);
	// 获取被代理类加载器,所有接口
    ClassLoader loader = realSubject.getClass().getClassLoader();
    Class<?>[] interfaces = realSubject.getClass().getInterfaces();
	
	// 生成代理类
    Subject subject = (Subject)Proxy.newProxyInstance(loader, interfaces, handler);
	// 调用代理类
    String ctl = subject.hello("ctl");
}

结果输出

begin invoke...
hello...
end invoke...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值