Freemarker的get-method无需"get" [英] Freemarker get-method without "get"
问题描述
如何使用以下语法访问方法/字段:
${object.foo}
?
我想要的是:
如果有一个名为foo的公共字段,则返回值,
否则,如果有一个名为getFoo()的吸气剂,则它将调用并返回调用结果,
否则,如果有一个名为foo()的方法,则它将调用并返回调用结果.
Freemarker中有可能吗?
How can I access method/field, using the following syntax:
${object.foo}
?
What i want is:
if there is a public field, named foo, then it's value returns,
else if there is a getter, named getFoo(), then it calls and result of call returns,
else if there is a method, named foo(), then it calls and result of call returns.
Is it possible in Freemarker?
推荐答案
由于您可以编写自己的ObjectWrapper
实现,因此有可能,尽管如果您需要多个object.foo
来工作(例如,公开方法等),则可以进行编写对象包装程序可以是很多的工作.因此,也许最好的折衷方法是使用DefaultObjectWrapper
或BeansWrapper
.在哪里配置FreeMarker:
Since you can write your own ObjectWrapper
implementation it's possible, although if you need more than object.foo
to work (like, exposing methods etc.) writing an object wrapper can be a lot of work. So, maybe a good compromise is using DefaultObjectWrapper
or BeansWrapper
. Where you configure FreeMarker:
BeansWrapper bw = new DefaultObjectWrapper() {
@Override
protected void finetuneMethodAppearance(
Class clazz, Method m, MethodAppearanceDecision decision) {
if (m.getDeclaringClass() != Object.class
&& m.getReturnType() != void.class
&& m.getParameterTypes().length == 0) {
String mName = m.getName();
if (!(mName.startsWith("get")
&& (mName.length() == 3
|| Character.isUpperCase(mName.charAt(3))))) {
decision.setExposeMethodAs(null);
try {
decision.setExposeAsProperty(new PropertyDescriptor(
mName, clazz, mName, null));
} catch (IntrospectionException e) { // Won't happen...
throw new RuntimeException(e);
}
}
}
}
};
bw.setExposeFields(true);
cfg.setObjectWrapper(bw);
优先级并不完全是您想要的. object.foo
将按以下顺序尝试操作:getFoo()
,foo()
,foo
The priorities aren't exactly what you wanted though. object.foo
will try things in this order: getFoo()
, foo()
, foo
这篇关于Freemarker的get-method无需"get"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!