newInstance已过时, 被@Deprecated
class.newInstance()在java9时被@Deprecated
今天在用jdk17的反射时, 发现神器newInstance()竟然已过时, 被@Deprecated了
查看源码:
@SuppressWarnings("removal")
@CallerSensitive
@Deprecated(since="9")
public T newInstance()
throws InstantiationException, IllegalAccessException
{......}
/**
* Creates a new instance of the class represented by this {@code Class}
* object. The class is instantiated as if by a {@code new}
* expression with an empty argument list. The class is initialized if it
* has not already been initialized.
*
* @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}.
*
* <p>The call
*
* <pre>{@code
* clazz.newInstance()
* }</pre>
*
* can be replaced by
*
* <pre>{@code
* clazz.getDeclaredConstructor().newInstance()
* }</pre>
*
* The latter sequence of calls is inferred to be able to throw
* the additional exception types {@link
* InvocationTargetException} and {@link
* NoSuchMethodException}. Both of these exception types are
* subclasses of {@link ReflectiveOperationException}.
*
* @return a newly allocated instance of the class represented by this
* object.
* @throws IllegalAccessException if the class or its nullary
* constructor is not accessible.
* @throws InstantiationException
* if this {@code Class} represents an abstract class,
* an interface, an array class, a primitive type, or void;
* or if the class has no nullary constructor;
* or if the instantiation fails for some other reason.
* @throws ExceptionInInitializerError if the initialization
* provoked by this method fails.
* @throws SecurityException
* If a security manager, <i>s</i>, is present and
* the caller's class loader is not the same as or an
* ancestor of the class loader for the current class and
* invocation of {@link SecurityManager#checkPackageAccess
* s.checkPackageAccess()} denies access to the package
* of this class.
*/
@SuppressWarnings("removal")
@CallerSensitive
@Deprecated(since="9")
public T newInstance()
throws InstantiationException, IllegalAccessException
{
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
checkMemberAccess(sm, Member.PUBLIC, Reflection.getCallerClass(), false);
}
// Constructor lookup
Constructor<T> tmpConstructor = cachedConstructor;
if (tmpConstructor == 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 = getReflectionFactory().copyConstructor(
getConstructor0(empty, Member.DECLARED));
// Disable accessibility checks on the constructor
// access check is done with the true caller
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<>() {
public Void run() {
c.setAccessible(true);
return null;
}
});
cachedConstructor = tmpConstructor = c;
} catch (NoSuchMethodException e) {
throw (InstantiationException)
new InstantiationException(getName()).initCause(e);
}
}
try {
Class<?> caller = Reflection.getCallerClass();
return getReflectionFactory().newInstance(tmpConstructor, null, caller);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
}
使用 class.getDeclaredConstructor(…构造参数类).newInstance(…参数);
例如
构造方法无参
Class.forName("全类名").getDeclaredConstructor().newInstance();
Class.forName(Thread.currentThread().getStackTrace()[1].getClassName()).getDeclaredConstructor().newInstance();
try {
Class.forName(Thread.currentThread().getStackTrace()[1].getClassName()).getDeclaredConstructor().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
Class.forName(Thread.currentThread().getStackTrace()[1].getClassName()).getDeclaredConstructor().newInstance();
} catch (Exception e) { e.printStackTrace();}
有一个String参数的构造方法
Frame frame =
(Frame)Class.forName("java.awt.Frame")
.getDeclaredConstructor(String.class)
.newInstance("Frame标题");