无忧论文网 · 始于1999 · 学术论文辅导与论文发表推荐服务

计算机类翻译论文:运行期类型鉴定

栏目
论文
具体类型
文献翻译
语言
中文
用途
范文参考
更新
关键词
活动期类型鉴定翻译
分类标签
翻译相关英语论文翻译
原站著录信息
原编号
lw201006031406538757
原文字数
19,090 字
原文件格式
DOC
原库登记日期
2010-06-03

摘要

运行期类型鉴定的概念初看非常简单——手上只有基础类型的一个句柄时,利用它判断一个对象的正确类型。 然而,对RTTI的需要暴露出了面向对象设计许多有趣的问题,并把程序的构造问题正式摆上了桌面。 本章将讨论如何利用Java在运行期间查找对象和类信息。这主要采取两种形式:一种是“传统”RTTI,它假定我们已在编译和运行期拥有所有类型;另一种是Java1.1特有的“反射”机制,利用它可在运行期独立查找类信息。首先讨论“传统”的RTTI,再讨论反射问题。 Detecting types The idea of run-tim…

运行期类型鉴定的概念初看非常简单——手上只有基础类型的一个句柄时,利用它判断一个对象的正确类型。
然而,对RTTI的需要暴露出了面向对象设计许多有趣的问题,并把程序的构造问题正式摆上了桌面。
本章将讨论如何利用Java在运行期间查找对象和类信息。这主要采取两种形式:一种是“传统”RTTI,它假定我们已在编译和运行期拥有所有类型;另一种是Java1.1特有的“反射”机制,利用它可在运行期独立查找类信息。首先讨论“传统”的RTTI,再讨论反射问题。


Detecting types
The idea of run-time type identification (RTTI) seems fairly simple at first: it lets you find the exact type of an object when you only have a reference to the base type.
However, the need for RTTI uncovers a whole plethora of interesting (and often perplexing) OO design issues, and raises fundamental questions of how you should structure your programs.
This chapter looks at the ways that Java allows you to discover information about objects and classes at run-time. This takes two forms: “traditional” RTTI, which assumes that you have all the types available at compile-time and run-time, and the “reflection” mechanism, which allows you to discover class information solely at run-time. The “traditional” RTTI will be covered first, followed by a discussion of reflection.
The need for RTTI
Consider the now familiar example of a class hierarchy that uses polymorphism. The generic type is the base class Shape, and the specific derived types are Circle, Square, and Triangle:
 
This is a typical class hierarchy diagram, with the base class at the top and the derived classes growing downward. The normal goal in object-oriented programming is for the bulk of your code to manipulate references to the base type (Shape, in this case), so if you decide to extend the program by adding a new class (Rhomboid, derived from Shape, for example), the bulk of the code is not affected. In this example, the dynamically bound method in the Shape interface is draw( ), so the intent is for the client programmer to call draw( ) through a generic Shape reference. draw( ) is overridden in all of the derived classes, and because it is a dynamically bound method, the proper behavior will occur even though it is called through a generic Shape reference. That’s polymorphism.
Thus, you generally create a specific object (Circle, Square, or Triangle), upcast it to a Shape (forgetting the specific type of the object), and use that anonymous Shape reference in the rest of the program.
The Class object
To understand how RTTI works in Java, you must first know how type information is represented at run-time. This is accomplished through a special kind of object called the Class object, which contains information about the class. (This is sometimes called a meta-class.) In fact, the Class object is used to create all of the “regular” objects of your class.
There’s a Class object for each class that is part of your program. That is, each time you write and compile a new class, a single Class object is also created (and stored, appropriately enough, in an identically named .class file). At run-time, when you want to make an object of that class, the Java Virtualwww.51lunwen.org Machine (JVM) that’s executing your program first checks to see if the Class object for that type is loaded. If not, the JVM loads it by finding the .class file with that name. Thus, a Java program isn’t completely loaded before it begins, which is different from many traditional languages.
Once the Class object for that type is in memory, it is used to create all objects of that type.
Each of the classes Candy, Gum, and Cookie have a static clause that is executed as the class is loaded for the first time. Information will be printed to tell you when loading occurs for that class. In main( ), the object creations are spread out between print statements to help detect the time of loading.
A particularly interesting line is:
Class.forName("Gum");
This method is a static member of Class (to which all Class objects belong). A Class object is like any other object and so you can get and manipulate a reference to it. (That’s what the loader does.) One of the ways to get a reference to the Class object is forName( ), which takes a String containing the textual name (watch the spelling and capitalization!) of the particular class you want a reference for. It returns a Class reference.
The output of this program for one JVM is:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie

You can see that each Class object is loaded only when it’s needed, and the static initialization is performed upon class loading.
Class literals
Java provides a second way to produce the reference to the Class object, using a class literal. In the above program this would look like:
which is not only simpler, but also safer since it’s checked at compile-time. Because it eliminates the method call, it’s also more efficient.
Class literals work with regular classes as well as interfaces, arrays, and primitive types. In addition, there’s a standard field called TYPE that exists for each of the primitive wrapper classes. The TYPE field produces a reference to the Class object for the associated primitive type, such that:
... 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
My preference is to use the “.class” versions if you can, since they’re more consistent with regular classes.
Checking before a cast
So far, you’ve seen RTTI forms including:
1. The classic cast; e.g., “(Shape),” which uses RTTI to make sure the cast is correct and throws a ClassCastException if you’ve performed a bad cast.
2. The Class object representing the type of your object. The Class object can be queried for useful run-time information.
In C++, the classic cast “(Shape)” does not perform RTTI. It simply tells the compiler to treat the object as the new type. In Java, which does perform the type check, this cast is often called a “type safe downcast.” The reason for the term “downcast” is the historical arrangement of the class hierarchy diagram. If casting a Circle to a Shape is an upcast, then casting a Shape to a Circle is a downcast. However, you know a Circle is also a Shape, and the compiler freely allows an upcast assignment, but you don’t know that a Shape is necessarily a Circle, so the compiler doesn’t allow you to perform a downcast assignment without using an explicit cast.
There’s a third form of RTTI in Java. This is the keyword instanceof that tells you if an object is an instance of a particular type. It returns a boolean so you use it in the form of a question, like this:
if(x instanceof Dog)
  ((Dog)x).bark();
The above if statement checks to see if the object x belongs to the class Dog before casting x to a Dog. It’s important to use instanceof before a downcast when you don’t have other information that tells you the type of the object; otherwise you’ll end up with a ClassCastException.
Ordinarily, you might be hunting for one type (triangles to turn purple, for example), but you can easily tally all of the objects using instanceof. Suppose you have a family of Pet classes:
package c12;

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; } ///:~

The Counter class is used to keep track of the number of any particular type of Pet. You could think of it as an Intege