简体   繁体   中英

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. But now such fields are being ignored.

The version i am using is 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;

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 .

In this case, you can change MY_ARRAY 's Signature to public static Integer[] MY_ARRAY .

Integer wraps the int value in an 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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