Proxy 示例

本文介绍了一个Java代理模式的具体实现案例,通过定义接口`ProxyInterface`及其实现类`ProxyImpl`,并使用动态代理实现对其方法的增强。该示例展示了如何通过反射创建代理对象,并在目标方法调用前后增加自定义的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

见附件,可运行,本人亲写亲测。

package com.test.proxy;

public interface ProxyInterface {

public void realMethod();

}


package com.test.proxy;

public class ProxyImpl implements ProxyInterface {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

public void realMethod(){
System.out.println("method in real Impl.");
}


}


package com.test.proxy;

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

public class proxyImplHandler implements InvocationHandler{

public ProxyInterface impl;
proxyImplHandler(ProxyInterface impl){
this.impl=impl;
}

@Override
public Object invoke(Object obj, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
System.out.println("Before realmethod invoke........");
method.invoke(this.impl, args);
System.out.println("after realmethod invoke........");
return null;
}

}


package com.test.proxy;

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

public class ProxyTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ProxyInterface imp =new ProxyImpl();
InvocationHandler handler = new proxyImplHandler(imp);
ProxyInterface o = (ProxyInterface)Proxy.newProxyInstance(
imp.getClass().getClassLoader(),
imp.getClass().getInterfaces(),
handler);
o.realMethod();

}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值