Thinking in Java--type information rtti

Source: Internet
Author: User

Thinking in java– type information

Personally feel the more difficult part of Java, in the look at some Netty source code found in fact this piece is very practical.

This chapter focuses on Rtti and reflection. Say your own understanding first.
Rtti is an execution-time recognition. is implemented in C + + with virtual, which ignores the object's detailed type information at compile time, assuming we already know it and identifying it in detail at execution time.

The Java reflection mechanism is in the execution state, and for arbitrary classes, all the properties and methods of the class can be known. For arbitrary an object. is able to invoke its arbitrary method and properties, such that the dynamic acquisition of information and the ability to dynamically invoke the object's method is called the Java reflection mechanism

Class Object

The class object is used to create all of the "general" objects of the class. Java uses the class object to perform its rtti.
What is a class object
Java is a purely object-oriented language. In Java, everything is an object, that is, class, and we generate a. class file (Javac hello.java-> hello.class) after compiling each class file (each object). The *.class file is the class object, when we are going to use the Hello class file for the first time. The class loader of the JVM loads the Hello.class file, feeling that the class object is a stencil. Used for the production of objects.
Note: Constructors are also static methods

Examples:
 PackageOnefour_chapter;/** * Created by WWH on 15-8-7. * *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");NewCandy (); System.out.println ("After creating Candy");Try{Class.forName ("Gum"); }Catch(ClassNotFoundException e) {System.out.println ("not found Gum"); } System.out.println ("after Class.forName (\" gum\ ")");NewCookies (); System.out.println ("After create Cookie"); }}


I run out of results and inconsistencies in the book because the Class.forName () parameter requirement is a fully qualified name and my code is in the package. It can be preceded by a package name, such as the following
Class.forName ("Package name". Gum ");

Key points:

Static code block

The static modified code block is only 类被载入时 executed and executed once. Typically used to initialize static variables and invoke static methods, no matter how many times you new, a class is only loaded once in the JVM's declaration cycle.
The constructor is also a static method, so test t = new Test (), the JVM loads the class object (. class file) of the test class the first time the object is created, and the class object, like any other object, can manipulate its references. Forname () is one way to get a class object reference.
Class.forName () Returns the class reference of the object, from which we can obtain a lot of information to choose something at execution time. Much like C + + 's type_traits. Note Classes created with newinstance () must have a default constructor

Static statement block
The static statement block executes when the class is loaded. Be executed only once
When I write encapsulated database connection pool in singleton mode, the new one database connection pool is written in the static code block, which ensures that the connection pool is initialized when the class is loaded and is initialized only once. Note When visiting static constants. Suppose the compiler can calculate it. is not loaded)

Class loading: Java loads A. class file under Terminal. The purpose of the Java command is to start the virtual machine. The virtual machine reads the contents of the bytecode (. class file) from the disk into the virtual machine and saves the process by streaming it.

class literal Constants

Java also provides a way to generate references to class objects, such as literal constants, classname.class, for example, Hello.class. It is safer and more efficient and does not wrap with a try statement. So generally we do not use forname (), which can be used for classes, interfaces, arrays. Basic type. It is recommended to use the. Class form: Class executes "as lazy as possible" initialization, while forname () initializes immediately
There are 3 preparation tasks to use for the class. Loading –> Connection –> initialization

the class reference of the Paradigm

A class reference always points to a class object that can make an instance of the class. and includes all the method code that can be used for these instances. It also includes static members of the class, so the class reference represents the exact type of the object it points to. The object is an object of class.
Adding a generic syntax to a class reference is only for compiler type checking. It says Rtti and reflection are all executed. Now we have a few limitations at compile time. More assurance of the correctness of the implementation
To relax the limit when using the class reference of the paradigm. Wildcards can be used, but they are combined with wildcards and extends keywords. Create a range.
Class

ImportJava.util.ArrayList;ImportJava.util.List;/** * Created by WWH on 15-8-7. * *Class countedinteger{Static{System.out.println ("Class loading"); }Private Static LongCounterPrivate Final Longid = counter++; PublicStringtoString() {returnLong.tostring (ID); }} Public  class filledlist<T> {    PrivateClass<t> type;/ * constructor. The parameter is a qualified class object, and we can specify it when instantiating the * /     Public filledlist(class<t> type) { This. type = type; } PublicList<t>Create(intnelements) {list<t> result =NewArraylist<t> ();Try{ for(inti =0; i < nelements;            i++) {Result.add (type.newinstance ()); }        }Catch(Exception e) {Throw NewRuntimeException (); }returnResult } Public Static void Main(string[] args) {/ * Execute the Qualified type and pass the. Class as the constructor's number of parameters * /filledlist<countedinteger> FL =NewFilledlist<countedinteger> (Countedinteger.class); System.out.println (Fl.create ( the)); }}

The third form of Rtti in Java is instanceof, which returns a Boolean value that tells us that the object is not a particular instance.
if (obj instanceof Dog) obj.exe ();
Instanceof has a stricter limit and can only compare it to a named type. and cannot compare with Fclass objects
The Class.isinstance () method provides a way to test the object dynamically.

Thinking in Java--type information Rtti

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.