在Java 9 之后通过newInstance
实例化对象时,显示该方式已过期:
通过提示信息可以看到:推荐getDeclaredConstructor().newInstance()
package mybatis.ui;
import java.lang.reflect.InvocationTargetException;
class Person{
public void eat(){
System.out.println("I am hungry");
}
}
public class Test {
public static void main(String[] args) {
try {
// Person instance = (Person) Class.forName("mybatis.ui.Person").newInstance();
Person instance = (Person) Class.forName("mybatis.ui.Person").getDeclaredConstructor().newInstance();
instance.eat();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}