我认为这是不可能的,但让我们尝试一下:
是否可以编写例程analyzeArrayList() 以这种方式打印 ArrayList 的维度 和列表的底部类型。
示例代码应打印:
Dimension = 2 and Bottom type = class java.lang.Float
Dimension = 3 and Bottom type = class java.lang.Integer
我们假设参数 s 始终是 ArrayList 的实例, 不是其他类型的实例。请注意,列表可以为空,但不能为空。
void analyzeArrayList(Object s)
{
int dimension;
String typeString;
//<Some code here!>
System.out.println("Dimension = "+dimension+" and Bottom type = "+typeString);
}
Object s = new ArrayList<ArrayList<Float>>();
Object t = new ArrayList<ArrayList<ArrayList<Integer>>>();
.
.
analyzeArrayList(s);
analyzeArrayList(t);
对此的评论:
有趣的是,如果你有一个带有字段的对象
ArrayList<ArrayList<Float>>
然后就可以写方法了
void analyzeArrayList(Field s)
如果你知道 Field 代表 ArrayList。
最佳答案
这是不可能的,因为 type erasure 。
Java 仅在编译时考虑泛型。如果您有List<String>
和List<Integer>
,编译器知道列表来自不同的类型,这使得它能够在每个实例的基础上创建某种类型的类型安全环境。由于类型删除,在运行时,两个列表就像都包含对象并且彼此等效。
关于java - 反射(reflect)通用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13709387/