java通过反射创建对象-Java面试题:动态创建对象已加注释
*******************************************************************
新建类DynamicCreateObject.java,具体代码如下(动态创建对象已加注释):
*******************************************************************
public class DynamicCreateObject {
public static void main(String[] args) {
try {
Student stu = (Student) (Class.forName("Student").newInstance()); //由类名动态创建对象
stu.setName("Godwin");
stu.setGender("male");
System.out.println("姓名:" + stu.getName() + ", 性别:"
+ stu.getGender());
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
String gender;
public Student() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
*******************************************************************
运行结果如下:
*******************************************************************
姓名:Godwin, 性别:male