为什么 ArrayList class 没有 newInstance() 方法?
Why doesn't ArrayList class have a newInstance() method?
只是一个理论问题,该方法不应该调用空构造函数并因此 return 一个空列表吗?
方法 newInstance()
属于名为 Class
的 class。 Javadoc:
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.
所以这两个是等价的:
ArrayList a = new ArrayList();
ArrayList b = ArrayList.class.newInstance();
您可以对每个 class 执行此操作,但不建议这样做,因为您会失去编译时安全性(如果没有无参数构造函数,它可能会在 运行 时失败)并且无法跟踪使用情况。
只是一个理论问题,该方法不应该调用空构造函数并因此 return 一个空列表吗?
方法 newInstance()
属于名为 Class
的 class。 Javadoc:
Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list.
所以这两个是等价的:
ArrayList a = new ArrayList();
ArrayList b = ArrayList.class.newInstance();
您可以对每个 class 执行此操作,但不建议这样做,因为您会失去编译时安全性(如果没有无参数构造函数,它可能会在 运行 时失败)并且无法跟踪使用情况。