Thinking in Java--type information rtti

Source: Internet
Author: User

Thinking in java– type information

Personal feel Java in the more difficult part of, in the read some Netty source found in fact this piece is very useful.

This chapter focuses on Rtti and reflection. Say your own understanding first.
Rtti is runtime recognition, which is implemented in C + + with virtual, ignoring the object's specific type information at compile time, assuming we already know it and identifying it specifically at runtime.

The Java reflection mechanism is actually running state, for any class, can know all the properties and methods of this class, for any one object, can invoke its arbitrary methods and properties, the dynamic acquisition of information and the function of the method of dynamic call object is called the Java reflection mechanism

Class Object

The class object is used to create all the "general" objects of the class. Java uses the class object to perform its rtti.
What is a class object
Java is a pure object-oriented language, in Java, everything is an object, that is, class, for each class file (each object) compiled we will generate a. class file (Javac hello.java-> hello.class), *. The class file is the class object, and when we first use the Hello class file, the JVM's classloader will load the Hello.class file, feeling that the class object is a mold that is used to produce the object.
Note: Constructors are also static methods

Example:
 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 ran out of results and inconsistencies in the book because the Class.forName () parameter requirement is a fully qualified name, my code in the package, preceded by the package name, as follows
Class.forName ("Package name". Gum ");

Key points:

Static code block

Static modified code blocks are executed only 类被加载时 once, and are 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 is like any other object, we can manipulate its reference, forname () is one way to get a class object reference.
Class.forName () Returns the class reference of the object, from which we can obtain very much information to choose something at runtime, much like the type_traits of C + +. Note Classes created with newinstance () must have a default constructor

Static statement block
Static statement blocks are executed when the class loads. 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 loads and is initialized only once. (Note that when a static constant is accessed, it is not loaded if the compiler can calculate it)

Class loading: Under Terminal Java loading. class files, the role of the Java command is to start the virtual machine, and the virtual machine reads the contents of the bytecode (. class file) from the disk into the virtual machine and saves the process.

class literal Constants

Java also provides a way to generate references to class objects, such as literal constants, classname.class, such as Hello.class, which are safer and more efficient and do not wrap around a try statement. So generally we do not use forname (), which can be used for classes, interfaces, arrays, basic types. It is recommended to use the. Class form, where the. class executes "as lazy as possible" initialization, while forname () initializes immediately
There are 3 preparations to use the class, load –> connection –> Initialize

the class reference of the Paradigm

A class reference always points to a class object that can make an instance of the class and contain all the method code that can be used for those instances. It also contains the static members of the class, so the class reference represents the exact type of the object it points to, which is an object of class.
Adding a generic syntax to a class reference is only for compiler type checking, which says that Rtti and reflection are both run-time, and now we have some limitations in compiling, which guarantees the correctness of the operation.
To relax the restrictions when using the class reference of the paradigm, you can use wildcards, or use wildcards with the extends keyword to 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, we can specify 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) {/ * Perform a qualified type and pass the. class as a parameter to the constructor * /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 more restrictive limit that can only be compared with named types, not with Fclass objects
The Class.isinstance () method provides a way to dynamically test an object.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.