首页 > 技术文章 > 使用Class.newInstance创建的对象无法调用类中的方法

sgKurisu 2021-03-07 20:19 原文

使用构造器的newInstance方法创建对象时,例如

Class<?> c1 = Class.forName("com.reflect.Student");
Constructor<?> constructor = c1.getDeclaredConstructor(String.class, int.class);
Object s1 = constructor.newInstance("AA", 11); 

此时s1方法无法调用Student类的getName方法,原因是创建s1是为Object类,因此无法使用Student类的方法,应该为

Student s1 = (Student) constructor.newInstance("AA", 11); 

推荐阅读