这篇文章主要介绍了Java进阶教程之运行时类型识别RTTI机制,在Java运行时,RTTI维护类的相关信息,比如多态(polymorphism)就是基于RTTI实现的,需要的朋友可以参考下
运行时类型识别(RTTI, Run-Time Type Identification)是Java中非常有用的机制,在Java运行时,RTTI维护类的相关信息。
多态(polymorphism)是基于RTTI实现的。RTTI的功能主要是由Class类实现的。
Class类
Class类是"类的类"(class of classes)。如果说类是对象的抽象和集合的话,那么Class类就是对类的抽象和集合。
每一个Class类的对象代表一个其他的类。比如下面的程序中,Class类的对象c1代表了Human类,c2代表了Woman类。
public class Test
{
public static void main(String[] args)
{
Human aPerson = new Human();
Class c1 = aPerson.getClass();
System.out.println(c1.getName());
Human anotherPerson = new Woman();
Class c2 = anotherPerson.getClass();
System.out.println(c2.getName());
}
}
class Human
{
/**
* accessor
*/
public int getHeight()
{
return this.height;
}
/**
* mutator
*/
public void growHeight(int h)
{
this.height = this.height + h;
}
private int height;
}
class Woman extends Human
{
/**
* new method
*/
public Human giveBirth()
{
System.out.println("Give birth");
return (new Human());
}
}
以上就是Java进阶教程之运行时类型识别RTTI机制的详细内容,更多请关注0133技术站其它相关文章!