11.1 对RTTI 的需要
11.1 对RTTI 的需要
请考虑下面这个熟悉的类结构例子,它利用了多态性。常规类型是

这是一个典型的类结构示意图,基础类位于顶部,衍生类向下延展。面向对象编程的基本目标是用大量代码控制基础类型(这里是
所以,我们一般创建一个特定的对象(Circle,Square,或者
作为对多态性和上溯造型的一个简要回顾,可以象下面这样为上述例子编码(若执行这个程序时出现困难,请参考第
//: Shapes.java
package c11;
import java.util.*;
interface Shape {
void draw();
}
class Circle implements Shape {
public void draw() {
System.out.println("Circle.draw()");
}
}
class Square implements Shape {
public void draw() {
System.out.println("Square.draw()");
}
}
class Triangle implements Shape {
public void draw() {
System.out.println("Triangle.draw()");
}
}
public class Shapes {
public static void main(String[] args) {
Vector s = new Vector();
s.addElement(new Circle());
s.addElement(new Square());
s.addElement(new Triangle());
Enumeration e = s.elements();
while(e.hasMoreElements())
((Shape)e.nextElement()).draw();
}
} ///:~
基础类可编码成一个
每个衍生类都覆盖了基础类
用
在目前这种情况下,
现在的局面会由多态性控制,而且会为
然而,若碰到一个特殊的程序设计问题,只有在知道常规指针的确切类型后,才能最容易地解决这个问题,这个时候又该怎么办呢?举个例子来说,我们有时候想让自己的用户将某一具体类型的几何形状(如三角形)全都变成紫色,以便突出显示它们,并快速找出这一类型的所有形状。此时便要用到
为理解
对于作为程序一部分的每个类,它们都有一个
一旦那个类型的
若这种说法多少让你产生了一点儿迷惑,或者并没有真正理解它,下面这个示范程序或许能提供进一步的帮助:
//: SweetShop.java
// Examination of the way the class loader works
class Candy {
static {
System.out.println("Loading Candy");
}
}
class Gum {
static {
System.out.println("Loading Gum");
}
}
class Cookie {
static {
System.out.println("Loading Cookie");
}
}
public class SweetShop {
public static void main(String[] args) {
System.out.println("inside main");
new Candy();
System.out.println("After creating Candy");
try {
Class.forName("Gum");
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
System.out.println(
"After Class.forName(\"Gum\")");
new Cookie();
System.out.println("After creating Cookie");
}
} ///:~
对每个类来说(Candy,
Class.forName("Gum");
该方法是
该程序在某个
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
可以看到,每个
Loading Candy
Loading Cookie
inside main
After creating Candy
Loading Gum
After Class.forName("Gum")
After creating Cookie
看来
- 类标记
在
这样做不仅更加简单,而且更安全,因为它会在编译期间得到检查。由于它取消了对方法调用的需要,所以执行的效率也会更高。
类标记不仅可以应用于普通类,也可以应用于接口、数组以及基本数据类型。除此以外,针对每种基本数据类型的封装器类,它还存在一个名为
……等价于……
... is equivalent to ...
boolean.class
Boolean.TYPE
char.class
Character.TYPE
byte.class
Byte.TYPE
short.class
Short.TYPE
int.class
Integer.TYPE
long.class
Long.TYPE
float.class
Float.TYPE
double.class
Double.TYPE
void.class
Void.TYPE
迄今为止,我们已知的
在
if(x instanceof Dog)
((Dog)x).bark();
将
我们最一般的做法是查找一种类型(比如要变成紫色的三角形
//: PetCount.java
// Using instanceof
package c11.petcount;
import java.util.*;
class Pet {}
class Dog extends Pet {}
class Pug extends Dog {}
class Cat extends Pet {}
class Rodent extends Pet {}
class Gerbil extends Rodent {}
class Hamster extends Rodent {}
class Counter { int i; }
public class PetCount {
static String[] typenames = {
"Pet", "Dog", "Pug", "Cat",
"Rodent", "Gerbil", "Hamster",
};
public static void main(String[] args) {
Vector pets = new Vector();
try {
Class[] petTypes = {
Class.forName("c11.petcount.Dog"),
Class.forName("c11.petcount.Pug"),
Class.forName("c11.petcount.Cat"),
Class.forName("c11.petcount.Rodent"),
Class.forName("c11.petcount.Gerbil"),
Class.forName("c11.petcount.Hamster"),
};
for(int i = 0; i < 15; i++)
pets.addElement(
petTypes[
(int)(Math.random()*petTypes.length)]
.newInstance());
} catch(InstantiationException e) {}
catch(IllegalAccessException e) {}
catch(ClassNotFoundException e) {}
Hashtable h = new Hashtable();
for(int i = 0; i < typenames.length; i++)
h.put(typenames[i], new Counter());
for(int i = 0; i < pets.size(); i++) {
Object o = pets.elementAt(i);
if(o instanceof Pet)
((Counter)h.get("Pet")).i++;
if(o instanceof Dog)
((Counter)h.get("Dog")).i++;
if(o instanceof Pug)
((Counter)h.get("Pug")).i++;
if(o instanceof Cat)
((Counter)h.get("Cat")).i++;
if(o instanceof Rodent)
((Counter)h.get("Rodent")).i++;
if(o instanceof Gerbil)
((Counter)h.get("Gerbil")).i++;
if(o instanceof Hamster)
((Counter)h.get("Hamster")).i++;
}
for(int i = 0; i < pets.size(); i++)
System.out.println(
pets.elementAt(i).getClass().toString());
for(int i = 0; i < typenames.length; i++)
System.out.println(
typenames[i] + " quantity: " +
((Counter)h.get(typenames[i])).i);
}
} ///:~
在
当然,这个例子只是一个构想——最好在每个类型里添加一个
- 使用类标记
//: PetCount2.java
// Using Java 1.1 class literals
package c11.petcount2;
import java.util.*;
class Pet {}
class Dog extends Pet {}
class Pug extends Dog {}
class Cat extends Pet {}
class Rodent extends Pet {}
class Gerbil extends Rodent {}
class Hamster extends Rodent {}
class Counter { int i; }
public class PetCount2 {
public static void main(String[] args) {
Vector pets = new Vector();
Class[] petTypes = {
// Class literals work in Java 1.1+ only:
Pet.class,
Dog.class,
Pug.class,
Cat.class,
Rodent.class,
Gerbil.class,
Hamster.class,
};
try {
for(int i = 0; i < 15; i++) {
// Offset by one to eliminate Pet.class:
int rnd = 1 + (int)(
Math.random() * (petTypes.length - 1));
pets.addElement(
petTypes[rnd].newInstance());
}
} catch(InstantiationException e) {}
catch(IllegalAccessException e) {}
Hashtable h = new Hashtable();
for(int i = 0; i < petTypes.length; i++)
h.put(petTypes[i].toString(),
new Counter());
for(int i = 0; i < pets.size(); i++) {
Object o = pets.elementAt(i);
if(o instanceof Pet)
((Counter)h.get(
"class c11.petcount2.Pet")).i++;
if(o instanceof Dog)
((Counter)h.get(
"class c11.petcount2.Dog")).i++;
if(o instanceof Pug)
((Counter)h.get(
"class c11.petcount2.Pug")).i++;
if(o instanceof Cat)
((Counter)h.get(
"class c11.petcount2.Cat")).i++;
if(o instanceof Rodent)
((Counter)h.get(
"class c11.petcount2.Rodent")).i++;
if(o instanceof Gerbil)
((Counter)h.get(
"class c11.petcount2.Gerbil")).i++;
if(o instanceof Hamster)
((Counter)h.get(
"class c11.petcount2.Hamster")).i++;
}
for(int i = 0; i < pets.size(); i++)
System.out.println(
pets.elementAt(i).getClass().toString());
Enumeration keys = h.keys();
while(keys.hasMoreElements()) {
String nm = (String)keys.nextElement();
Counter cnt = (Counter)h.get(nm);
System.out.println(
nm.substring(nm.lastIndexOf('.') + 1) +
" quantity: " + cnt.i);
}
}
} ///:~
在这里,typenames(类型名)数组已被删除,改为从
也可以看到,
- 动态的
instanceof
//: PetCount3.java
// Using Java 1.1 isInstance()
package c11.petcount3;
import java.util.*;
class Pet {}
class Dog extends Pet {}
class Pug extends Dog {}
class Cat extends Pet {}
class Rodent extends Pet {}
class Gerbil extends Rodent {}
class Hamster extends Rodent {}
class Counter { int i; }
public class PetCount3 {
public static void main(String[] args) {
Vector pets = new Vector();
Class[] petTypes = {
Pet.class,
Dog.class,
Pug.class,
Cat.class,
Rodent.class,
Gerbil.class,
Hamster.class,
};
try {
for(int i = 0; i < 15; i++) {
// Offset by one to eliminate Pet.class:
int rnd = 1 + (int)(
Math.random() * (petTypes.length - 1));
pets.addElement(
petTypes[rnd].newInstance());
}
} catch(InstantiationException e) {}
catch(IllegalAccessException e) {}
Hashtable h = new Hashtable();
for(int i = 0; i < petTypes.length; i++)
h.put(petTypes[i].toString(),
new Counter());
for(int i = 0; i < pets.size(); i++) {
Object o = pets.elementAt(i);
// Using isInstance to eliminate individual
// instanceof expressions:
for (int j = 0; j < petTypes.length; ++j)
if (petTypes[j].isInstance(o)) {
String key = petTypes[j].toString();
((Counter)h.get(key)).i++;
}
}
for(int i = 0; i < pets.size(); i++)
System.out.println(
pets.elementAt(i).getClass().toString());
Enumeration keys = h.keys();
while(keys.hasMoreElements()) {
String nm = (String)keys.nextElement();
Counter cnt = (Counter)h.get(nm);
System.out.println(
nm.substring(nm.lastIndexOf('.') + 1) +
" quantity: " + cnt.i);
}
}
} ///:~
可以看到,