本课题回答处理抽象方法类型;但如何代理方法的非抽象部分? Implementing abstract methods at runtime?
如何执行以下操作以致电sayHello()
?
package cglibtest;
import java.lang.reflect.Method;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
public class CGLibTest
{
public static void main(String... args)
{
MyAbstract instance = (MyAbstract)Enhancer.create(MyAbstract.class, new MyInterceptor(42));
System.out.println("Value from instance: " + instance.valueMethod());
System.out.println("Value from instance: " + instance.sayHello());
}
public static class MyInterceptor implements MethodInterceptor
{
private final Object constantValue;
public MyInterceptor(Object constantValue)
{
this.constantValue = constantValue;
}
@Override
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable
{
if ("valueMethod".equals(method.getName()))
return(constantValue);
else
return(null);
}
}
public static abstract class MyAbstract
{
public abstract int valueMethod();
public String sayHello() { return "Hello" };
}
}
答案 0 :(得分:1)
您创建的拦截器已经覆盖了所有方法,无论是否为abstract
。您似乎错过的是如何调用已覆盖的原始方法:
public Object intercept(Object obj, Method method, Object[] args,
MethodProxy proxy) throws Throwable
{
if ("valueMethod".equals(method.getName()))
return constantValue;
else if("sayHello".equals(method.getName())) {
System.out.println("before original sayHello()");
// equivalent of saying super.sayHello() inside subclass
Object result=proxy.invokeSuper(obj, args);
System.out.println("after original sayHello()");
return result;
}
else return null;
}