Java runtime type recognition (RTTI)-1-Class and instanceof

Source: Internet
Author: User

Three methods:
1. Traditional type conversion
2. Query Class objects
3. instanceof

1. Traditional type conversion
String string = (String) s;
2. Query Class objects
First, you need to understand the java. lang. Class.

When running, the type information indicates that an instance of the Class is completed.
Java uses the Class object to execute its RTTI, even for transformation-like operations.
Each Class has a Class Object (stored in a Class object with the same name. to generate the class object, the JVM running this program will use a subsystem called "class Loader ".
(For the content of the Class Loader, I will introduce it later)

Once a Class object of a Class is loaded into the memory, it is used to create all objects of the Class.
[Java]
Static {
//...
}
The code is executed when the class is loaded for the first time.

Let's take a look at the sample code in think in java.
[Java]
Public class Candy {
Static {
System. out. println ("Loading Candy ");
}
}
[Java]
Public class Gum {
Static {
System. out. println ("Loading Gum ");
}
}

Public class SweetShop {
[Java]
Public static void main (String [] args ){
System. out. println ("inside main ");
New Candy ();
System. out. println ("After creating Candy ");
Try {
Class. forName ("Gum ");
} Catch (ClassNotFoundException e ){
E. printStackTrace ();
}
System. out. println ("After Class. forName (\" Gum \")");
}
Running result
Inside main
Loading Candy
After creating Candy
Loading Gum
After Class. forName ("Gum ")


The Class is loaded only when needed. Otherwise, the Loading Candy and Loading Gum should be output first.
Pay attention to Class. forName ("Gum ");
As shown in the log, this statement also makes the class Gum loaded.

The following two methods can be used to generate Class references:
1. newInstance ()
Note the following when using newInstance:
A. The class must have a default constructor. Otherwise, java. lang. InstantiationException will occur.
B. The default constructor must be accessible. Otherwise, java. lang. IllegalAccessException may occur.
2. Literal Constants
It is simpler and safer to use a class literal constant: because it is checked during compilation, try catch is not required.
The Class will not be initialized using the Class literal.
The class literal can be used for classes, interfaces, arrays, and basic types.
For the package Class of the basic data TYPE, a standard field TYPE. TYPE is a reference pointing to the Class of the corresponding basic data TYPE.
... Is equivalent...
Boolean. class Boolean. TYPE
Char. class Character. TYPE
Byte. class Byte. TYPE
Short. class Short. TYPE
Int. class Integer. TYPE
Long. class Long. TYPE
Float. class Float. TYPE
Double. class Double. TYPE
Void. class Void. TYPE
3. instanceof
We can use the keyword instanceof for type check (x instanceof Gum), which returns a boolean
We can also use Dynamic boolean java. lang. Class. isInstance (Object obj) for type check.

Equivalence Between instanceof and Class
[Java]
Public class Test {
Static class Base {}
Static class Derived extends Base {}

Static void test (Object x ){
System. out. println ("Testing x of type" + x. getClass ());
System. out. println ("x instanceof Base" + (x instanceof Base ));
System. out. println ("x instanceof Derived" + (x instanceof Derived ));
System. out. println ("Base. isInstance (x)" + (Base. class. isInstance (x )));
System. out. println ("Derived. isInstance (x)" + (Derived. class. isInstance (x )));
System. out. println ("x. getClass () = Base. class" + (x. getClass () = Base. class ));
System. out. println ("x. getClass () = Derived. class" + (x. getClass () = Derived. class ));
System. out. println ("x. getClass (). equals (Base. class)" + (x. getClass (). equals (Base. class )));
System. out. println ("x. getClass (). equals (Derived. class)" + (x. getClass (). equals (Derived. class )));
}

Public static void main (String [] args ){
Test. test (new Base ());
System. err. println ("----------------------------");
Test. test (new Derived ());
}
}
Result
Testing x of type class Test $ Base
X instanceof Base true
X instanceof Derived false
Base. isInstance (x) true
Derived. isInstance (x) false
X. getClass () = Base. class true
X. getClass () = Derived. class false
X. getClass (). equals (Base. class) true
X. getClass (). equals (Derived. class) false
----------------------------
Testing x of type class Test $ Derived
X instanceof Base true
X instanceof Derived true
Base. isInstance (x) true
Derived. isInstance (x) true
X. getClass () = Base. class false
X. getClass () = Derived. class true
X. getClass (). equals (Base. class) false
X. getClass (). equals (Derived. class) true

We can see that the instanceof and isInstance () results are the same, and the equals and = results are the same.
Instanceof is a type check and = is an object comparison. do not consider inheritance or other relationships.
I personally think it is better to understand


Class Loader
Here, I will only post my notes, and then describe them in detail when summarizing the virtual machine. The link will be provided here.

 
Author: su1216

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.