英文:
convert back to class type List from GenericEntity - anonymous class
问题
我在下面的代码中的第7行遇到了类转换异常。我已经编写了第1-3行来提供来自rest服务调用的数据,这些行不能从我的方面进行更改。我必须将响应转换为List
List<Integer> lstInt = new ArrayList<Integer>();
lstInt.add(1);
lstInt.add(2);
GenericEntity<List<Integer>> gEntity = new GenericEntity<List<Integer>>(lstInt) {};
System.out.println(gEntity.getClass()); //输出com.org.dept.proj.MyClass$12
List<Integer> output = (List<Integer>) gEntity; // 类转换异常
System.out.println(output);
英文:
I am getting class cast exception at line 7 in the code below. I have written line 1-3 to provide data that comes from a rest service call and these line can't be changed from my side. I must cast the response to List<integer>
List<Integer> lstInt = new ArrayList<Integer>();
lstInt.add(1);
lstInt.add(2);
GenericEntity<List<Integer>> gEntity = new GenericEntity<List<Integer>>(lstInt) {};
System.out.println(gEntity.getClass()); //prints com.org.dept.proj.MyClass$12
List<Integer> output = (List<Integer>) gEntity; // class cast exception
System.out.println(output);
答案1
得分: 1
谢谢 @Michael。我必须在 gEntity
上运行 getEntity
,然后根据文档进行类型转换。
List<Integer> lstInt = new ArrayList<Integer>();
lstInt.add(1);
lstInt.add(2);
GenericEntity<List<Integer>> gEntity = new GenericEntity<List<Integer>>(lstInt) {};
System.out.println(gEntity.getEntity());
List<Integer> output = (List<Integer>) gEntity.getEntity();
System.out.println(output);
英文:
Thank you @Michael. I had to run a getEntity
on gEntity
and then cast it as per the documentation
List<Integer> lstInt = new ArrayList<Integer>();
lstInt.add(1);
lstInt.add(2);
GenericEntity<List<Integer>> gEntity = new GenericEntity<List<Integer>>(lstInt) {};
System.out.println(gEntity.getEntity());
List<Integer> output = (List<Integer>) gEntity.getEntity();
System.out.println(output);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论