如何将列表从子类泛型转换为父类泛型? [英] How do I cast a List from a subclass generic to a parent class generic?
问题描述
我正在修改开放的JDK以添加功能,但是我两次都遇到了这种情况,但没有好的解决方案.
I'm modifying open JDK to add features and I've run into this twice with no good solution.
有一个名为JCStatement
的类,该类扩展了JCTree
.
There's a class named JCStatement
which extends JCTree
.
问题:我想将List<JCStatement>
转换为List<JCTree>
.
很明显,一个类可以引用其扩展名之一,但是当我将其放在List上时,它就是行不通的.
It's clear that a class can reference one of its extensions, but when I have it on a List, it just doesn't work.
我曾经使用过:(List<JCTree>)((List<?>)params)
进行强制转换,但不能在ant上构建. IDE向我发出以下警告:
I used: (List<JCTree>)((List<?>)params)
to cast, which works, but doesn't build on ant. IDE gives me the following warning:
Type safety: Unchecked cast from List<capture#1-of ?> to List<JCTree>
所以这必须以某种方式解决.
So this must be worked around somehow.
感谢您的帮助.
推荐答案
列表或一般类型的通用类型集合似乎是一个问题.
This seems to be an issue with the List, or generic types collections as general.
有史以来最简单的解决方案:
Simplest solution ever:
ListBuffer<JCTree> ls = new ListBuffer<JCTree>();
for(JCVariableDecl v : params){ ls.append(v); }
return ls.toList();
这篇关于如何将列表从子类泛型转换为父类泛型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!