简体   繁体   English

从Jtwig模板访问静态常量数组

[英]Accessing static constant arrays from Jtwig template

So, I simply cannot gather access to values in constant static arrays. 因此,我根本无法收集对常量静态数组中的值的访问。

Let this be an array in my code: 让它成为我的代码中的数组:

public static int[] MY_ARRAY;

And this is how i trying to access that array: 这就是我试图访问该数组的方式:

{{ constant("com.package.configs.MainConfig.MY_ARRAY")[0] }}

This attempt leads to an error: 此尝试导致错误:

java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
    at org.jtwig.value.convert.collection.ArrayToCollectionConverter.convert(ArrayToCollectionConverter.java:11)
    at org.jtwig.value.convert.CompositeConverter.convert(CompositeConverter.java:15)
    at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:19)
    at org.jtwig.render.expression.calculator.MapSelectionExpressionCalculator.calculate(MapSelectionExpressionCalculator.java:12)
    at org.jtwig.render.expression.CalculateExpressionService.calculate(CalculateExpressionService.java:14)
...

I also tried to assign a constant to variable first, then accessing it, but nothing changed. 我还尝试过先给变量赋一个常量,然后再访问它,但没有任何改变。

Previously, in an older versions of JTwig i was able to access any public static field of a object that i passed to the model. 以前,在较旧的JTwig版本中,我能够访问传递给模型的对象的任何公共静态字段。 But now such fields are being ignored. 但是现在这些字段被忽略了。

The version i am using is 5.86.0. 我使用的版本是5.86.0。 Any idea on how to beat this, or at this moment it's technically impossible? 关于如何克服这一点的任何想法,或者目前在技术上是不可能的?

The exception 例外

java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object; java.lang.ClassCastException:[我无法转换为[Ljava.lang.Object;

means the array MY_ARRAY is an int -type array, and int is a primitive , thus it's not a sub type of Object , so you can not cast it to an Object -type array . 表示数组MY_ARRAY是一个int类型的数组,而int是一个原始类型 ,因此它不是Object的子类型,因此不能将其 MY_ARRAYObject类型的array

In this case, you can change MY_ARRAY 's Signature to public static Integer[] MY_ARRAY . 在这种情况下,您可以将MY_ARRAY的签名更改为public static Integer[] MY_ARRAY

Integer wraps the int value in an Object . Integerint值包装在Object

This is illustrated by the following example: 以下示例说明了这一点:

public static void main(String args[]) {
    int[] arr = new int[5];
    Integer[] arrI = new Integer[5];
    test(arr);  // error:The method test(Object[]) in the type Demo is not applicable for the arguments (int[])
    test(arrI); // ok
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM