2013-10-22 55 views
2

的所有实例,如果我实现了一些在MethodInterceptor如下:不CGLIB修改类

public class HashCodeAlwaysZeroMethodInterceptor implements MethodInterceptor { 

    public Object intercept(Object object, Method method, Object[] args, 
    MethodProxy methodProxy) throws Throwable { 

    if ("hashCode".equals(method.getName())) { 

     return 0; 
    } 

    return methodProxy.invokeSuper(object, args); 
    } 
} 

Object proxy = Enhancer.create(
    Object.class, 
    new HashCodeAlwaysZeroMethodInterceptor()); 

是对象的每个实例现在提高? IE:如果我做这样的事情:

class foo { foo(){} } 
foo myfoo = new foo(); 
int hash = myfoo.hashCode(); 
System.io.println(hash); //Prints 0 

它确实打印0?

回答

0

从API DOCS

创建

public static Factory create(java.lang.Class type, 
          Callback callback) 

助手方法来创建一个截获对象。为了更好地控制生成的实例 ,请使用Enhancer的新实例,而不是此静态方法。

Parameters: 
    type - class to extend or interface to implement 
    callback - the callback to use for all methods 

从它似乎回答你的问题的文档是肯定的

+0

它看上去仍然不清晰。 create()似乎返回一个可用于实例化增强对象的工厂......意味着您必须自己明确实例化它们 – Raindog