https://www.cnblogs.com/wxd0108/p/5685817.html
https://blog.csdn.net/hustzw07/article/details/72518298
#Java中创建对象的5种方式
使用new关键字 } → 调用了构造函数
使用Class类的newInstance方法 } → 调用了构造函数
使用Constructor类的newInstance方法 } → 调用了构造函数
使用clone方法 } → 没有调用构造函数
使用反序列化 } → 没有调用构造函数
##1.使用new关键字
这是最常见也是最简单的创建对象的方式了。通过这种方式,我们可以调用任意的构造函数(无参的和带参数的)。
Student student = new Student();
##2.Class类的newInstance方法
Student student2 = (Student)Class.forName(className).newInstance();
// 或者:
Student stu = Student.class.newInstance();
JDK1.8,class类的源码
public final class Class<T> implements java.io.Serializable,
GenericDeclaration,
Type,
AnnotatedElement {
// other code
public T newInstance()
throws InstantiationException, IllegalAccessException
{
// ...
// Constructor lookup
// other code
if (cachedConstructor == null) {
if (this == Class.class) {
throw new IllegalAccessException(
"Can not call newInstance() on the Class for java.lang.Class"
);
}
try {
// ...
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
// 1. 构造函数是公有的或者方法可见
// ...
cachedConstructor = c;
} catch (NoSuchMethodException e) {
throw (InstantiationException)
new InstantiationException(getName()).initCause(e);
}
}
Constructor<T> tmpConstructor = cachedConstructor;
// ...
// Run constructor
try {
return tmpConstructor.newInstance((Object[])null);// 2. 无参构造函数
} catch (InvocationTargetException e) {
// ...
}
}
// other code
}