Freemarker get-method without “get”

喜夏-厌秋 提交于 2019-12-11 07:44:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!