使用类字面常量

学习如何使用类字面常量重写 PetCount.java 示例是很有趣的。改写后的结果在各方面都显
得更加清晰:
//: c10:PetCount2.java
// Using class literals.
package c10;
import com.bruceeckel.simpletest.*;
import java.util.*;
public class PetCount2 {
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];
if(o instanceof Pet)
        ((Counter)map.get("class c10.Pet")).i++;
if(o instanceof Dog)
        ((Counter)map.get("class c10.Dog")).i++;
if(o instanceof Pug)
        ((Counter)map.get("class c10.Pug")).i++;
if(o instanceof Cat)
        ((Counter)map.get("class c10.Cat")).i++;
if(o instanceof Rodent)
        ((Counter)map.get("class c10.Rodent")).i++;
if(o instanceof Gerbil)
        ((Counter)map.get("class c10.Gerbil")).i++;
if(o instanceof Hamster)
        ((Counter)map.get("class c10.Hamster")).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)
    });
  } 
} ///:~
在这个例子中,typenames(类型名)数组已被移除,改为从 Class 对象获取类型名称。
注意,系统能够区分类和接口的不同。


你同时也可以看到,生成 petTypes 的代码不需要放在 try 语句块内,因为它会在编译期
得到检查,因此,它不会抛出任何异常,这与 Class.forName()不一样。


Pet 对象被动态创建以后,可以看到随机数字已经被限制在 1 至 petTypes.length 但不
包括零的范围内。因为零代表 Pet.class,而通用的 Pet 对象可能不会有人感兴趣。然而,

由于 Pet.class 也是 petTypes 的一部分,因此所有 Pet 都被计算在内。


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值