今天上课讲了Java中的一些反射知识。
随便练习了一下。
学生类:
public class Student {
public static int number;
static {
number = 0;
}
public Student() {
}
private String studentName;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
方法类:
public class ClassDemo {
static Student s2 = new Student();//创建这些变量,不管是类的类型还是基本数据类型,都不能放在代码块里。
static int a = 0;//代码块只能做基本的提前初始化工作
static {
System.out.println(Student.number);
s2.setStudentName("1111");
System.out.println(s2.getStudentName());
}
public static void main(String[] args) {
Student s = new Student();
Class c1 = Student.class;
System.out.println(c1);
Class c2 = s.getClass();
System.out.println(c2);
Class c3 = null;
try {
c3 = Class.forName("com.mijia.loading.Student");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(c3);
s2.setStudentName("niuyi");
System.out.println(s2.getStudentName());
Scanner sc = new Scanner(System.in);
int select = sc.nextInt();
if (select == 1) {
//Hotel h = new Hotel();//如果没有创建这个类,这样静态加载类就会报错
try {
Class h = Class.forName("com.mijia.loading.Hotel");//动态加载类,只有要加载的时候,它才会去判断有没有这个类
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
在这里,我没有创建Hotel类,但是可以用Class.forName来动态加载类,而且运行不会报错,这在开发中较为常用。