/*
*获得一个类实例的Class对象有三种常用方法
*1、调用从Object类中继承来的方法public Class getClass()
*以下两种方法是获得某个指定类的Class对象(如果知道类实例的确切类型)
*2、利用Class类的static方法forName(String className(需要带包名)),注意这个方法throws ClassNotFoundException
*3、利用类字面常量,类名.class,也会返回一个指定类的Class对象,它在编译时进行检查,不抛出任何异常
*进行类型比较的两类方法
*(一)比较某对象是否为指定类或其子类的对象
*假设对象x为class X的一个实例(X extends SuperX)
*1、利用instanceof关键字:x instanceof X == true x instanceof SuperX == true
*2、先利用上述三种方法之一获得Class对象的引用,再调用Class类的方法public boolean isInstance(Object o):
* x.getClass().isInstance(x)这是一句废话,呵呵。 X/SuperX.class.isInstance(x) == true Class.forName("X/SuperX").isInstance(x) == true
*(二)比较某对象是否为指定类的对象(不包括其基类)
*先利用上述三种方法之一获得Class对象的引用,再调用Class类的equals()方法(重写了Object类的equals()方法)或利用==比较符
*/
//GetAndCompareClass.java
//Show three menthod to get a Class object and whether an object is a object of the specific class
package com.msn.spaces.bryantd001;
class SuperX{}
class X extends SuperX{}
public class GetAndCompareClass{
public static Class getForName(String className){
try{
return Class.forName(className);
}catch(ClassNotFoundException e){
System.out.println("The class "+className +" cannot be found!!");
return null;
}
}
public static void main(String[] args){
SuperX x = new X();
System.out.println("Three method to get the x'Class object:");
System.out.println("The x is a object of "+x.getClass()+" class.");
System.out.println("The x is a object of "+X.class+" class.");
System.out.println("The x is also a object of "+getForName("com.msn.spaces.bryantd001.SuperX")+" class.");
System.out.println("Compare by the first way.");
System.out.println("The x is a object of X: "+(x instanceof X));
System.out.println("The x is a object of SuperX: "+(SuperX.class.isInstance(x)));
System.out.println("Compare by the second way.");
System.out.println("The x is a object of X: "+(x.getClass() == X.class));
System.out.println("The x is a object of SuperX: "+(x.getClass().equals(SuperX.class)));
}
}