问题
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?
回答1:
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);
The priorities aren't exactly what you wanted though. object.foo
will try things in this order: getFoo()
, foo()
, foo
来源:https://stackoverflow.com/questions/18918141/freemarker-get-method-without-get