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 Constructor's
// security check to work)

本文探讨了Java中newInstance()方法在类实例化中的作用,尤其是它如何通过获取cachedConstructor和创建构造函数来实现对象创建。分析了源码中的关键步骤,包括通过arrayContentsEq()找到合适的构造函数,以及利用ConstructorAccessor实例化构造函数以进行有参数或无参数的构造函数调用。

1345

被折叠的 条评论
为什么被折叠?



