Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String to Object conversion - not working in Java 11

Tags:

java-11

Below code snippet works fine in Java 1.8, but not working with Java 11 SDK.

 public static void main(String[] args) {

    String jsonText = "{\"user\":{\"name\":\"mrhaki\",\"age\":38,\"interests\":[\"Groovy\",\"Grails\"]}}";
    JsonSlurper jsonSlurper = new JsonSlurper();
    Object result = jsonSlurper.parseText(jsonText);

    Map jsonResult = (Map) result;
    Map user = (Map) jsonResult.get("user");
    String name = (String) user.get("name");
    Integer age = (Integer) user.get("age");
    List interests = (List) user.get("interests");

    assert name.equals("mrhaki");
    assert age == 38;
    assert interests.size() == 2;
    assert interests.get(0).equals("Groovy");
    assert interests.get(1).equals("Grails");
}

While trying to run the above code snippet in Java 11, getting the below exception.

Exception in thread "main" java.lang.ClassCastException: class [B cannot be cast to class [C ([B and [C are in module java.base of loader 'bootstrap')
    at groovy.json.internal.FastStringUtils$StringImplementation$1.toCharArray(FastStringUtils.java:88)
    at groovy.json.internal.FastStringUtils.toCharArray(FastStringUtils.java:175)
    at groovy.json.internal.BaseJsonParser.parse(BaseJsonParser.java:103)
    at groovy.json.JsonSlurper.parseText(JsonSlurper.java:208)
    at groovy.json.JsonSlurper$parseText.call(Unknown Source)
    at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:45)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
    at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:116)
    at Test.main(Test.groovy:9)

Please explain the cause and reason behind this ? Also, what is the alternative way to convert String to Object in Java 11 ?

Thanks in advance!

like image 802
Janani Sampath Kumar Avatar asked Oct 03 '18 06:10

Janani Sampath Kumar


1 Answers

The message “class [B cannot be cast to class [C” indicates that the method is trying to cast a byte[] array to a char[] array. Since the code location also has a name like FastStringUtils.toCharArray, I can guess what happens here.

This class seems to hack into the java.lang.String class and read its value field in a questionable attempt of performance improvement. Since Java 9, this internal array is a byte[] array instead of a char[] array, which makes this hack fail at runtime.

You need an updated version of the library or a configuration option disabling that hack, if it exists.

like image 140
Holger Avatar answered Jan 25 '23 13:01

Holger