Java9 Class类 newInstance 过时 替换的方法

Java9 Class类 newInstance 过时

Class.forName("类的全限定名").newInstance();

被替换为

Class.forName("类的全限定名").getDeclaredConstructor().newInstance();

源码说明

    /**
     * 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>
     */
发布了80 篇原创文章 · 获赞 13 · 访问量 9257

猜你喜欢

转载自blog.csdn.net/qq_39424178/article/details/98121862