gpt4 book ai didi

java - Apache Velocity 自定义 Uberspect

转载 作者:行者123 更新时间:2023-11-29 05:55:02 25 4
gpt4 key购买 nike

来自 Apache 速度指南的属性查找规则是:

地址属性($object.address)

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

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

get(String name)

但是

get(String name, Object...params)

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

最佳答案

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

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

自定义 super 扇区

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());
}

}

关于java - Apache Velocity 自定义 Uberspect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12513495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com