"Java Programming Thought" (Second Edition) Chapter 12: Implementation Disease Identification (Part)

xiaoxiao2021-03-05  25

The initial idea of ​​RTTI is very simple: When there is a reference to the basic type of Base Type, the RTTI mechanism makes you find out the exact type referred to. There are two forms of RTTI in Java: traditional RTTI; reflection mechanism

Why use RTTI? The above purpose is the reason, such as downward transformation downcasting / forced transformation .class object and his loading time. How to get a class / object Class object? Class.Forname ("gum"); // does not require specific objects, but may result in abnormal execution period, such as getting the gum class x.class; x.getClass (); // Need to be specific object X

Before the transformation, the type check: (avoid the operation period abnormal classcastexception) 1. Traditional transformation (shape) .. 2. Operation Class object 3.InstanceOf if (x instanceof Dog) // x is a DOG object? Or do you have DOG derived objects?

Java uses the Class object to perform its RTTI mechanism - even if you do just the transformation action. Several useful functions in the class type GetInterfaces (): class [] // returns a Class object of a series of interfaces. NewInstance (): Object // Virtual constructor: I don't know what you specifically, but you give me a Static Class.Forname ("gum"): classisinterface (): bool // Judgment a Class object Whether it is interface.getname (): string // gets the name of the type belonging to the Class object. GetSuperclass () In short, with a class of Class objects, his ancestors can be found.

In fact. RTTI and polymorphism have a repetitive function, first try to use the polymorphism, and finally use RTTI, remember, do not abuse the RTTI.

转载请注明原文地址:https://www.9cbs.com/read-35775.html

New Post(0)