转换回从GenericEntity派生的类类型List – 匿名类

huangapple go评论65阅读模式
英文:

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&lt;Integer&gt; lstInt = new ArrayList&lt;Integer&gt;();
	lstInt.add(1);
	lstInt.add(2);

	GenericEntity&lt;List&lt;Integer&gt;&gt; gEntity = new GenericEntity&lt;List&lt;Integer&gt;&gt;(lstInt) {};
	System.out.println(gEntity.getClass()); //prints com.org.dept.proj.MyClass$12
	List&lt;Integer&gt; output = (List&lt;Integer&gt;) 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&lt;Integer&gt; lstInt = new ArrayList&lt;Integer&gt;();
		lstInt.add(1);
		lstInt.add(2);
		GenericEntity&lt;List&lt;Integer&gt;&gt; gEntity = new GenericEntity&lt;List&lt;Integer&gt;&gt;(lstInt) {};
		System.out.println(gEntity.getEntity());
		List&lt;Integer&gt; output = (List&lt;Integer&gt;) gEntity.getEntity();
		System.out.println(output);

huangapple
  • 本文由 发表于 2020年10月9日 17:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64277410.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定