读到这几章的时候,才真正决定水比较深,可能真的需要多使用之后再回头来看这些才会理解
- Class.forName("...")会加载类,而是用字面的.class不会引发初始化。对于static final的编译时常量的引用不会引发初始化
- 使用类的三步准备工作:加载,链接,初始化(惰性)
- 泛化的Class引用: Class<Number> numClass = int.class 无法正常工作,虽然int是Number的子类,但是Integer Class不是Number Class的子类,可以使用 Class<? extends Number>
import java.util.*; 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 n){ List<T> result = new ArrayList<T>(); try{ for(int i = 0; i < n; 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.class); System.out.println(fl.create(10)); } }
- instanceof 和 == 比较的区别是 instanceof保持了类型的概念,而== 比较实际的Class对象,没有考虑继承