Java中newInstance()是创建类的重要方法,特别是利用工厂来创建类,这一方法基本是必不可少的,其内部原理并不十分复杂。
首先我们随便写个User类,使用newInstance()方法创建对象
User.class.newInstance();
查看newInstance()源码,核心部分是获取cachedConstructor以及实际创建构造函数
获取cachedConstructor
// Constructor lookup
if (cachedConstructor == null) {
if (this == Class.class) {
throw new IllegalAccessException(
"Can not call newInstance() on the Class for java.lang.Class"
);
}
try {
Class<?>[] empty = {};
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
// Disable accessibility checks on the constructor
// since we have to do the security check here anyway
// (the stack depth is wrong for the C