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

 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).

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值