Java Programming Ideas (14)--Type information Rtti (1)

Source: Internet
Author: User

It's strange when translators translate, Runtime type information (RTTI) allows you to discover and use type information while a program is running.


Run-Time Type information ( original translation without parentheses in the content, runtime type information, referred to as Rtti, the personal feel that this is better) can let you find and use the type information while the program is running. The immediate appearance of Rtti is confusing.


1) Why do I need rtti

In the previous polymorphic example:

public class Everytv {public    static void Tvshow (TV TV) {        tv.show ();    }     public static void Main (string[] args) {        tvshow (new LeTV ());        Tvshow (New MiTV ());        Tvshow (New Santv ());}    }
transform a variety of TV subclasses into TVs, which is a form of use for Rtti, run-time type information, and all types of conversions are properly checked at run time. That is, at run time, identify the type of an object.


2) Class object

Java uses class objects to perform its rtti, classes are part of a program, each class has a class object, and each time a new class is written and compiled, a class object is created, which is actually saved in the. class file of the same name. The generation of this class object is actually a subsystem of the JVM (the Java Virtual machine) that uses the ClassLoader.


All classes are dynamically loaded into the JVM when they are first used, and the class is loaded when the program creates the first reference to a static member of the class, so that the constructor is a static method of the class, although there is no static modification, because new object is a reference to the static member of the class.


Dynamic load enable behavior (feels weird), English words: Dynamic loading enables behavior that's difficult or impossible toduplicate in a statically loaded LA Nguage like C + +.

Dynamic load allowed behavior is difficult or impossible to replicate in statically loaded languages such as C + + (this translates better).


The class loader first checks to see if the class object is already loaded. If it is not loaded, the. class file is found based on its name. Class object is loaded into memory and is used to create all objects of this class

Package Son;class first{    static{        System.out.println ("First load");}    } Class second{    static{        System.out.println ("Second load");}    } public class TestClass {public    static void Main (string[] args) {        System.out.println ("main");        New first ();        System.out.println ("first after");        try {            class.forname ("son. Second ");        } catch (ClassNotFoundException e) {            System.out.println ("not Found");        }        System.out.println ("second after");        System.out.println ("End");    
this time specially added package name, because more and more feel strange, no package name when class is not found. Second.class.getName () was used in advance, and the class name is son. Second. It would be a try.

Depending on the statement inside the static method, you can know the order in which the classes are loaded, Class.forName ("Second")

All class objects belong to class.

static Class<?> forName(String className)Returns the Class object associated with the class or interface with the given string name.
Zhenyang Gets the class object that provides the name. Due to the existence of the package, no second object was found when the package name was not written, so it is not found.


Class.forName () can obtain a reference to the desired class object without requiring us to hold the object of that type. If you already have an object, you can get the class reference by GetClass ().

There is a problem with the example in the book (themain statement repeats ).

Package Son;public interface Fire {}public interface water {}class gun{    Gun () {         System.out.println ("init");   }}public class Deathgun extends Gun implements                                         water,fire{static void Printinfo (Class C) {System.out.println ("Class name:" + c.getname () + "Interface?"                                         +c.isinterface () + "\nsimplename" +c.getsimplename () +    "CanonicalName" +c.getcanonicalname ());        } public static void Main (string[] args) {Class c = null; try {c = class.forname ("son.        Deathgun ");            } catch (ClassNotFoundException e) {System.out.println ("not Found");        System.exit (1);        } printinfo (c);        For (Class cc:c.getinterfaces ()) {printinfo (cc);        } Class father = C.getsuperclass ();        Object o = null; try {             o = Father.newinstance ();        } catch (Instantiationexception e) {//TODO auto-generated catch block E.printstacktrace ();        } catch (Illegalaccessexception e) {//TODO auto-generated catch block E.printstacktrace ();    } printinfo (O.getclass ()); }}
Forname As mentioned above to have the package name, the whole is called the CanonicalName, the canonical class name, the translator translates to the fully qualified name. Getsimplename () Gets the class name, whether Isiterface () is an interface. Getinterfaces returns the Class object.


stop first stop, now someone a bit disorderly, re-thinking, Class,class, Class, object, will make a mess. Class is a keyword, which defines a class, class is an instance of a class , and class is one of the classes, Why class, because he can do some serious work-such as reflection.


The Rtti mentioned earlier is actually done by a special object called the class object, because class is a class, but differs from the information about the entire class,class containing class. Class A, if we write and compile a, we create a class object that is stored in the. class file. When a static member reference is created, the class is loaded, the static member is a property or method owned by the class and multiple objects, which can be called with the class name + static member name, and the class should be loaded as the new object, which illustrates that the constructor is also a static method. Class.forName returns a reference to a class object that is loaded if the class is not loaded.


Continue, newinstance really like the Netizen said similar Factory mode, specially in the constructor write an output, newinstance will print out, Father just class reference, compile period does not have further type information, The object reference after new is actually referring to the gun.


3) class literal constants

Oh, before dizzy me, you will find Class,getclass (),. Class,class These look like, look at the idea of re-rationale before, will be good to understand.

This is another way to generate a reference to a class object:

A.class;

Simple security, compiler check, can be applied to interfaces, arrays and basic types, basic types of wrapper classes also have a standard field type, which is also a reference to the corresponding class object.

Int.class is equivalent to Integer.type.

But this does not initialize the class object. So the static method in the class will not be printed like forname.


Preparation before using the class:

(1) load, by the ClassLoader, find the bytecode, and create the object from the bytecode.

(2) Link, verify bytecode, allocate space for static domain.

(3) initialization, with super-class words to initialize it, execute static initializer and static initialization block.


Initialization is deferred and deferred to a static method, which naturally includes the previously mentioned constructor or the first reference to a very few static domains for initialization.

package son;    Class a{static final int show= 1;    static{System.out.println ("init a");    }}class b{static int showb= 1;    static{System.out.println ("Init B");    }}class c{static int showc= 1;    static{System.out.println ("Init C");        }}public class Classinitialization {public static void main (string[] args) {class Inita = A.class;        System.out.println ("after a");        System.out.println (a.show);        Class INITB = B.class;        System.out.println ("after B");        System.out.println (B.SHOWB); try {Class ININTC = Class.forName ("son.        C ");        } catch (ClassNotFoundException e) {//TODO auto-generated catch block E.printstacktrace (); }}}result:after a1after binit b1init c 
before I saw this, I first tried class Inita = A.class, and did not print the statement in static, thinking that I understand the concept of the wrong, originally really true, really do not initialize first.


In order to produce a Class reference, Class.forName () is initialized immediately. But the initialization of the. class is inert. Static final is a compile-time constant, does not require a class to initialize, and Class B, no final, read the domain when the first link, storage space allocation and initialization. So B is initialized, and the print statement is also typed.



This chapter is my understanding of the shortcomings of the place, there are reflection and dynamic agents, so back to my original purpose, revisit the front, learn to understand before.

Java Programming Ideas (14)--Type information Rtti (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.