- 首先这个函数或属性都是用来获得一个类型的Class对象。每一个类型在java虚拟机中都对应一个Class对象,该对象用于java虚拟机加载一个该类型的对象到内存中。
- 其次getClass都是用于一个Custom object的,.class用于一个类型(系统封装或者用户自定义类型),比如People类型,而forName 是Class类型的一个静态函数,用于获得一个类型的Class对象。
- getClass返回的Class对象,是在运行时确定的,而另外两个都是在编译的时候确定的。
假如我们有两个类型People和Student,其中student继承自People。如果执行下面的代码:
People people =
new
Student();
try{
System.out.println(Class.forName("People") == People.class);
System.out.println(Class.forName("People") == people.getClass());
System.out.println(people.getClass() == People.class);
System.out.println(Class.forName("People"));//People
System.out.println(people.getClass());//Student
System.out.println(People.class);//People
}catch(Exception e)
{
e.printStackTrace();
}
Student student = new Student();
try{
System.out.println(Class.forName("Student") == Student.class);
System.out.println(Class.forName("Student") == student.getClass());
System.out.println(student.getClass() == Student.class);
System.out.println(Class.forName("Student"));//Student
System.out.println(student.getClass());//Student
System.out.println(Student.class);//Student
}catch(Exception e)
{
e.printStackTrace();
}
-----------------------------------------------------
Silence, the way to avoid many problems;
Smile, the way to solve many problems;