1

从 Apache 速度指南属性查找规则是:

对于地址属性($object.address)

getaddress()
getAddress()
get("address")
isAddress()

我想更改获取规则以接受可变参数对象参数。所以它不会调用

get(String name)

get(String name, Object...params)

我知道这可以通过创建自定义 ubespector 来完成。但我完全不知道怎么做。

4

1 回答 1

3

最后经过 2 天的挖掘,我能够制作自定义的 Uberspector。如果没有找到相应的方法,将调用“run(String, Object[])”方法。标准的“get(String)”将调用

run(name, new Object[]{});

自定义Ubersector

import java.lang.reflect.Method;
import org.apache.velocity.util.introspection.Info;
import org.apache.velocity.util.introspection.UberspectImpl;
import org.apache.velocity.util.introspection.VelMethod;

public class CustomUberspector extends UberspectImpl {

public VelMethod getMethod(Object obj, String methodName, Object[] args, Info i)
        throws Exception  {

        if (obj == null) return null;

        VelMethod vm = super.getMethod(obj, methodName, args, i);
        if(vm != null) return vm;

        Object[] iargs = {methodName, new Object[] {}} ;
        Method m = introspector.getMethod(obj.getClass(), "run", iargs);
        if (m != null) return new PortalVelMethodImpl(m, methodName);

        return null;
}

public class PortalVelMethodImpl extends VelMethodImpl {
    final Method method;
    final String name;

    public PortalVelMethodImpl(Method m, String methodName) {
        super(m);
        method = m;
        name   = methodName;            
    }

    protected Object doInvoke(Object o, Object[] actual) throws Exception  {
        /* "run" method argumens are String and Object[] so we need to get plain Object[] array
         * From [Arg0,[Arg1..ArgN] to [Arg0,Arg1..ArgN]
         * */
        List<Object> args = new ArrayList<Object>();
        if(actual.length >= 1) {
            args.add(actual[0]);

            if(actual.length >= 2) {
                Object[] nestedArgs = (Object[])actual[1];
                for(int i=1; i<nestedArgs.length; i++) args.add(nestedArgs[i]);
            }
        }

        return method.invoke(o, name, args.toArray());
    }

}

}

于 2012-09-25T10:35:14.943 回答