[书摘]Issues about RTTI (Run Time Type Identification)

来源:互联网 发布:华工网络教育平台v3 编辑:程序博客网 时间:2024/05/30 23:18

 class Test2
{
 static {
  System.out.println("Loading Test2 ...");
  }
 }

public  class Test {
 static {
  System.out.println("Loading Test ...");
  }

public static void main(String[] args)
  {
 Object[] obj={new Test(),new Test2()};
System.out.println("*************** Using  'instanceof'  to judge the type ******************");
    for(int i=0;i<obj.length;i++){
     if(obj[i] instanceof Test)System.out.println("obj["+i+"]"+" is a Test object");  //named type意思是instanceof后面的参数必须是一个类的名字,而不能是一个实例。
     if(obj[i] instanceof Test2)System.out.println("obj["+i+"]"+" is a Test2 object");
  }

System.out.println("************* Using method  'isInstance'  to judge the type *************");
    Class[] cls={
  // Class literals:
  Test.class,
  Test2.class
  };
    for(int j=0;j<obj.length;j++){
         for(int k=0;k<obj.length;k++)
       if(cls[k].isInstance(obj[j]))System.out.println("obj["+j+"]"+" is a "+cls[k]+" object");
  }  //比较而言,Class类的isInstance()方法要灵活得多

  }
}

================================================================================

There’s a rather narrow restriction on instanceof: You can compare it to a named type only, and not to a Class object. --------This means, if you use instanceof , you have to list all the class names you wanna compare with.

You can see that the isInstance( ) method has eliminated the need for the instanceof expressions. In addition, this means that you can add new objects simply by changing the obj array; the rest of the program does not need modification (as it did when using the instanceof expressions).

 

原创粉丝点击