前置
动态代理:字节码在使用时创建和加载,实现在不修改其他方法的基础上实现对该方法的增强。
代码描述
1、一个具有接口的类
// 一个接口的实现类
public class TestImpl implements Test{
/**
* 获取参数
* @param value
*/
public void getValue(int value){
System.out.println("我获得了一个值:"+value);
}
}
2、上述类的接口
public interface Test{
/**
* 获取值
* @param value
*/
void getValue(int value);
}
3、实现动态代理
public class Demo{
public static void main(String[] args){
// 匿名内部类中引用的对象需要用final修饰
final TestImpl testImpl = new TestImpl();
Test proxyTestImpl = (Test) Proxy.newProxyInstance(testImpl.getClass().getClassLoader(),testImpl.getClass().getInterfaces(),new InvocationHandler(){
@Override
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable{
Object returnValue = null;
Integer value = (Integer)args[0];
if("getValue".equals(Method.getName())){
returnValue = method.invoke(testImpl, value * 0.5);
}
return returnValue;
}
}
// 用代理对象,执行被代理对象的方法,并实现相关增强
proxyTestImpl.getValue(1000);
}
}