我们最近开始在接口(interface)中使用 java 8 默认方法,看起来 Freemarker 看不到它们:
${myRatings.notEmpty()}
The following has evaluated to null or missing:
==> myRatings.notEmpty
这很遗憾,因为我们在模板中调用了一堆方法。 有针对这个的解决方法吗?也许一些补丁?
互联网上谈论的大多是 getFoo() 默认方法,这确实没有多大意义,但我说的是常规方法调用,而不是 getter。
最佳答案
更新:FreeMarker 2.3.26 为此引入了一个解决方法。转自version history :
FREEMARKER-24: Added workaround (not enabled by default) to expose Java 8 default methods (and the bean properties they define) to templates, despite that
java.beans.Introspector
(the official JavaBeans introspector) ignores them, at least as of JRE 1.8.0_66. To enable this workaround, either increase the value of theincompatibleImprovements
constructor argument ofDefaultObjectWrapper
orBeansWrapper
used to 2.3.26, or set itstreatDefaultMethodsAsBeanMembers
setting totrue
. Note that if you leave theobject_wrapper
setting of theConfiguration
on its default, it's enough to increase theincompatibleImprovements
setting of theConfiguration
to 2.3.26, as that's inherited by the defaultobject_wrapper
.
原答案:
Freemarker 如何看待对象是基于 JavaBeans 规范的,它是许多 Java 技术的基石。它使用 java.beans.Introspector
对类进行内省(introspection)以确保一致性。显然,JavaBeans 不支持 Java 8 默认方法。 BeanInfo.getMethodDescriptors()
不返回默认方法,我们在使用 getter 的 BeanInfo.getPropertiesDescriptors()
中遇到了同样的问题。我不知道为什么标准 Java API(或 JavaBeans)的维护者会做出这样的决定……当然,Freemarker 迟早会不得不进行额外一轮的自省(introspection)以解决这些 JavaBeans 的限制。
关于java - Freemarker 和 java8 默认方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30503889/