动态的 instanceof

Class.isInstance 方法提供了一种动态地调用 instanceof 运算符的途径。于是所有
那些单调的 instanceof 语句都可以从 PetCount 例子中移除了。如下所示:
//: c10:PetCount3.java
// Using isInstance()
package c10;
import com.bruceeckel.simpletest.*;
import java.util.*;
public class PetCount3 {
private static Test monitor = new Test();
private static Random rand = new Random();
public static void main(String[] args) {
    Object[] pets = new Object[15];
    Class[] petTypes = {
      // Class literals:
      Pet.class,
      Dog.class,
      Pug.class,
      Cat.class,
      Rodent.class,
      Gerbil.class,
      Hamster.class,
    }; 
try {
for(int i = 0; i < pets.length; i++) {
        // Offset by one to eliminate Pet.class:
int rnd = 1 + rand.nextInt(petTypes.length - 1);
        pets[i] = petTypes[rnd].newInstance();
      } 
    } catch(InstantiationException e) {
      System.out.println("Cannot instantiate");
      System.exit(1);
    } catch(IllegalAccessException e) {
      System.out.println("Cannot access");
      System.exit(1);
    } 
    AssociativeArray map =
new AssociativeArray(petTypes.length);
for(int i = 0; i < petTypes.length; i++)
      map.put(petTypes[i].toString(), new Counter());
for(int i = 0; i < pets.length; i++) {
      Object o = pets[i];
      // Using Class.isInstance() to eliminate
      // individual instanceof expressions:
for(int j = 0; j < petTypes.length; ++j)
if(petTypes[j].isInstance(o))
          ((Counter)map.get(petTypes[j].toString())).i++;
    } 
    // List each individual pet:
for(int i = 0; i < pets.length; i++)
      System.out.println(pets[i].getClass());
    // Show the counts:
    System.out.println(map);
    monitor.expect(new Object[] {
new TestExpression("%% class c10\\." +
"(Dog|Pug|Cat|Rodent|Gerbil|Hamster)",
        pets.length),
new TestExpression("%% class c10\\." +
"(Pet|Dog|Pug|Cat|Rodent|Gerbil|Hamster) : \\d+",
        petTypes.length)
    });
  } 
} ///:~
可以看到 isInstance()方法使我们不再需要 instanceof 表达式。此外,这意味着如果
要求添加新类型的宠物,只需简单地改变 petTypes 数组即可;而毋需改动程序其他的部

分(但是在使用 instanceof 时这却是必需的)。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值