在《Thinking in Java》中,第 566 页给出了以下示例。
class CountedInteger {
private static long counter;
private final long id = counter++;
public String toString() { return Long.toString(id); }
}
public class FilledList<T> {
private Class<T> type;
public FilledList(Class<T> type) { this.type = type; }
public List<T> create(int nElements) {
List<T> result = new ArrayList<T>();
try {
for(int i = 0; i < nElements; i++)
result.add(type.newInstance());
} catch(Exception e) {
throw new RuntimeException(e);
}
return result;
}
public static void main(String[] args) {
FilledList<CountedInteger> fl = new FilledList<CountedInteger>(CountedInteger.class);
System.out.println(fl.create(15));
}
}
对于这个例子我有三个问题。
1)私有(private)Class类型有什么用?为什么是私有(private)的?
2) 为什么要执行以下操作,特别是“this.type = type;”
public FilledList(Class<T> type) { this.type = type; }
3)作者声称:
Notice that this class must assume that any type that it works with has a default constructor (one without arguments), and you’ll get an exception if that isn’t the case.
我不明白这个陈述是如何反射(reflect)在上面的例子中的。谢谢。
最佳答案
1) 不一定是这样,但这是您在 Java 中要做的事情之一——不要公开不需要公开的内容。
2) 将属性设置为构造函数的参数——这是基本的 Java。
3) 由于 type.newInstance()
调用;如果没有默认(无参数)构造函数,它将失败。
关于java - 关于说明通用类语法用法的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7599623/