Java class 类通过反射实例化对象
Class#newInstance方法已经被弃用了,从注释中可以看到推荐使用Constructor#newInstance方法生成实例,即直接通过构造方法生成实例:
// getConstructor 方法入参是可变长参数列表,对应类中构造方法的入参类型,这里使用无参构造。
// newInstance 返回的是泛型 T,取决于 clazz 的类型 Class<T>。这里直接用 Object 接收了。
Object instance = clazz.getConstructor().newInstance();
使用 getDeclaredConstructor方法还可获得 private的构造方法。
注释中弃用的理由:主要是绕过了编译时异常检查。
@deprecated This method propagates any exception thrown by the nullary constructor, including a checked exception.
Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler.
The {@link java.lang.reflect.Constructor#newInstance(java.lang.Object...) Constructor.newInstance} method avoids this problem by wrapping any exception thrown by the constructor in a (checked) {@link java.lang.reflect.InvocationTargetException}.
这种方式从各方面来看确实比以前的Class#newInstance要好不少。

浙公网安备 33010602011771号