Freemarker get-method without “get”

2019-08-03 08:41发布

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?

标签: freemarker
1条回答
来,给爷笑一个
2楼-- · 2019-08-03 09:12

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

查看更多
登录 后发表回答