A brief analysis of JDK source code base Class library in--java.lang package

Source: Internet
Author: User


Preface


Jdk,java Development Kit.

We must first realize that the JDK is just a Java base Class library, which is the base class library developed by Sun, and that's it, the JDK itself and the class library we write ourselves to summarize, technically, or at one level, that need to be compiled into bytecode, run in the JRE, The result of JDK compilation is Jre/lib Rt.jar, we learn to use it to deepen our understanding of Java and improve our Java coding level.

All articles in this series are based on a JDK version of 1.7.16.


The content of this section


In this section, we analyze the underlying class libraries that are included in the Java.lang package, and when we write a new class, the class is imported by default, so we don't have to write the import Java.lang.Integer such code, we still use integer this class, of course, if you display write import Java.lang.Integer also no problem, but, why superfluous?


Object


The default all classes inherit from Object,object No property, only method, its methods are mostly native method (that is, in other more efficient language, generally C is implemented well),

Object does not implement Clone (), implements the Hashcode (), the hash is the object instantiation in the heap memory address, with "= =" to compare two objects, is actually the comparison of the memory address is a, that is, hashcode () is equal,

By default, the Equals () method of an object is the same as the = = Symbol, which is the comparison of memory addresses, but some objects override the Equals () method, such as string, to achieve the same effect as comparing content

The other two methods wait () and notify () is related to multithreaded programming, multithreading inside synchronized is actually lock, the default is to use this when the lock, of course, can also use any object when the lock, wait () lock, Thread blocking, notify () unlocked, The thread that receives this notification runs. The following code example:

Class Test implements Runnable{private string Name;private object Prev;private Object Self;public Test (String name,object Prev,object self) {This.name=name;this.prev = Prev;this.self = self;} @Overridepublic void Run () {int count = 2;while (count>0) {synchronized (prev) {synchronized (self) {System.out.println (name+ ":" +count); count--;self.notify ();//self unlock}try{prev.wait ();//prev lock} catch (Interruptedexception e) { E.printstacktrace ();}}} public static void Main (string[] args) throws exception{object a = new object (); object B = new object (); object c = new OBJ ECT (); Test TA = new Test ("A", c,a); Test TB = new Test ("B", A/b); Test TC = new Test ("C", b,c); new Thread (TA). Start (); Thread.Sleep (ten); new Thread (TB). Start (); Thread.Sleep (ten); new Thread (TC). Start ();}}


The above code will be output sequentially: a:2, B:2, C:2, A:1, B: 1, C:1.


Class and Reflection classes


Java programs at run time each class will correspond to a class object, you can get information related to classes from the class object, class object stored in the method area (aka Non-heap, Permanent Generation), when we run the Java program, if the loaded jar package is very many, is greater than the specified permanent memory size, the PermGen error is reported, which is the total size of the class object, which exceeds the permanent generation memory.

Class classes are very useful, as we often use when we do type conversions, such as when using the thrift framework, it is often necessary to convert between objects of model type: Thrift objects and Java objects, to manually write a large number of patterned code, and then to write a tool for object conversion. In the case where the Thrift object is consistent with the property name of the Java object, you can use this tool to convert directly, using the methods in class and the contents of the Java.lang.reflect package.

About the Calss class, methods are numerous, not detailed. The code for this thrift tool is attached below.

Import Java.lang.reflect.field;import Java.lang.reflect.parameterizedtype;import Java.lang.reflect.type;import Java.text.parseexception;import Java.text.simpledateformat;import Java.util.arraylist;import java.util.Date; Import java.util.list;/** * Thrift prefix objects and objects that do not contain thrift prefixes are converted to each other. * Reference: * http://blog.csdn.net/it___ladeng/article/details/7026524 * http://www.cnblogs.com/jqyp/archive/2012/03/29/ 2423112.html * http://www.cnblogs.com/bingoidea/archive/2009/06/21/1507889.html * http://java.ccidnet.com/art/3539 /20070924/1222147_1.html * http://blog.csdn.net/justinavril/article/details/2873664 */public class Thriftutil { public static final Integer thrift_port = 9177;/** * THRIFT The instance of the generated class and the instance of the original class of the project convert and assign the value * 1. The name of the class's properties must be exactly the same * 2. The currently supported types are only: Byte, Short,int,long,double,string,date,list * 3. If there are specified columns, this column is true to assign a value, otherwise, NOT NULL is assigned * @param sourceObject * @param Targetclass * @param tothrift:true delegates convert Javaobject to Thriftobject,false delegate thriftobject into Javaobject, Thriftobject contains specified column * @return */public static Object Convert (Object sourceobject,class<?> Targetclass,boolean tothrift) {if (sourceobject==null) {return null;} For simple types, do not convert, directly return if (Sourceobject.getclass (). GetName (). StartsWith ("Java.lang")) {return sourceObject;} class<?> Sourceclass = Sourceobject.getclass (); field[] Sourcefields = Sourceclass.getdeclaredfields (); Object targetObject = null;try {targetObject = Targetclass.newinstance ();} catch (Instantiationexception E1) {e1.printstacktrace ();} catch (Illegalaccessexception E1) {e1.printstacktrace ();}; if (targetobject==null) {return null;} The for (Field Sourcefield:sourcefields) {try {////conversion filters out the thrift framework automatically generated objects if (Sourcefield.gettype (). GetName (). StartsWith (" Org.apache.thrift ") | | Sourcefield.getname (). substring (0,2). Equals ("__") | | ("Schemes,metadatamap,serialversionuid". IndexOf (Sourcefield.getname ())!=-1) | | (Sourcefield.getname (). IndexOf ("_fields")!=-1) | | (Sourcefield.getname (). IndexOf ("Specified")!=-1)) {continue;} Handles properties named dotnet sensitive characters, such as operatorstring sourcefieldname = Sourcefield.getname ();if (Sourcefieldname.equals ("operator")) {sourcefieldname = "_operator";} else {if (Sourcefieldname.equals ("_operator" ) {sourcefieldname = "operator";}} Locate the property with the same name in the target object field Targetfield = Targetclass.getdeclaredfield (sourcefieldname); sourcefield.setaccessible (true); Targetfield.setaccessible (TRUE); String sourcefieldsimplename = Sourcefield.gettype (). Getsimplename (). toLowerCase (). Replace ("integer", "int"); String targetfieldsimplename = Targetfield.gettype (). Getsimplename (). toLowerCase (). Replace ("integer", "int");// If the type of the two objects with the same name is exactly the same: boolean,string, and 5 numeric types: byte,short,int,long,double, and ListIf (Targetfieldsimplename.equals ( Sourcefieldsimplename)) {//For simple type, direct assignment if ("Boolean,string,byte,short,int,long,double". IndexOf ( Sourcefieldsimplename)!=-1) {Object o = sourcefield.get (sourceObject); if (o! = null) {Targetfield.set (TargetObject, O) ;//Handle the specified column, or assign a null value to a numeric object based on the specified column try{if (tothrift) {Field Targetspecifiedfield = Targetclass.getdeclaredfield (sourcefieldname+ "Specified"); if (Targetspecifiedfield! = Null) {targetspecifiedfield.setaccessible (true); Targetspecifiedfield.set (TargetObject, True);}} else {Field Sourcespecifiedfield = Sourceclass.getdeclaredfield (sourcefieldname+ "Specified"); if ( Sourcespecifiedfield! = null && "B,s,b,i,l,d". IndexOf (Targetfield.gettype (). Getsimplename (). substring (0,1) ) {!=-1) {sourcespecifiedfield.setaccessible (true); if (Sourcespecifiedfield.getboolean (sourceObject) ==false) { Targetfield.set (targetObject, NULL);}}} catch (Nosuchfieldexception e) {//Eats the nosuchfieldexception, achieves the effect: if the specified column does not exist, all columns are assigned a value of}}continue;} For ListIf (sourcefieldsimplename.equals ("list")) {@SuppressWarnings ("unchecked") list<object> Sourcesubobjs = (arraylist<object>) sourcefield.get (SourceObject), @SuppressWarnings ("unchecked") list<object> TARGETSUBOBJS = (arraylist<object>) targetfield.get (targetObject);//Key place, if it is a list type, get its generic type TargetType = Targetfield.getgenerictype ()//if is the type of the generic parameter if (TargetType instanceof Parameterizedtype) { Parameterizedtype pt = (PaRameterizedtype) targettype;//Gets the class type object in the generic type. class<?> C = (class<?>) pt.getactualtypearguments () [0]; if (sourcesubobjs!=null) {if (targetsubobjs==null) {targetsubobjs = new arraylist<object> ();} for (Object obj:sourcesubobjs) {targetsubobjs.add (CONVERT (Obj,c,tothrift));} Targetfield.set (TargetObject, TARGETSUBOBJS);}} Continue;}} Convert to thrift Auto-generated class: Thrift No date type, we uniformly require the date to be formatted as YYYY-MM-DD HH:mm:ss form if (tothrift) {if ("Sourcefieldsimplename.equals" Date ") &&targetfieldsimplename.equals (" string ")) {Date d = (date) sourcefield.get (sourceObject); if (d!=null) { SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Targetfield.set (Targetobject,sdf.format (d));} Continue;}} else {if (Sourcefieldsimplename.equals ("string") &&targetfieldsimplename.equals ("date")) {string s = (string) Sourcefield.get (SourceObject); if (s!=null) {SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); Targetfield.set (Targetobject,sdf.parse (s));} Continue;}} For other custom object Targetfield.set (targetObject, CONVERT (Sourcefield.get (sourceObject), Targetfield.gettype (), Tothrift));} catch (SecurityException e) {e.printstacktrace ();} catch (Nosuchfieldexception e) {e.printstacktrace ();} catch ( IllegalArgumentException e) {e.printstacktrace (),} catch (Illegalaccessexception e) {e.printstacktrace ();} catch ( ParseException e) {e.printstacktrace ();}} return targetObject;}}


Eight basic types of data
Class type Native type (primitive) Representative meaning
Boolean Boolean Boolean
Character Char A single character, such as ' a ', ' Medium '
Byte Byte 8-bit signed integer
Short Short 16-bit signed integer
Integer Int 32-bit signed integer
Long Long 64-bit signed integer
Float Float Single-precision floating point
Double Double Double-precision floating point

To understand the data type, it is necessary to understand a bit of coding (number in the computer 01 encoding) knowledge, the computer is 01 for all types, the first bit is the sign bit, the 0+1-,java is signed.

For numbers, the original code, the inverse code, and the complement are defined.

Positive number of the original code, anti-code and complement are the same, negative number of the anti-code is in addition to the sign bit, all bits reversed, complement is anti-code +1, in the case of byte type:

The number range that can be represented is -128~127, a total of 256 numbers, for 0~127, expressed as: 0000000~01111111, that is, 0~2^7-1, for negative numbers, -128~-1, expressed as follows:

-127~-1, the original code is 11111111~10000001, converted to complement is 10000001~11111111, then 10000000 for -128,-128 only complement, no original code and anti-code.

The complement is designed to:

Simplifies the rules of operation by taking the symbolic potential energy and the valid value parts together. The symbol bit in the number of complement machines is not imposed, it is a natural part of the data itself and can participate in the operation normally.

The subtraction operation is converted to addition operation, which further simplifies the circuit design of the computing device in the computer.

The inverse code is an intermediate transition between the original code and the complement, using less.

All of these transformations are carried out at the very bottom of the computer, and the original code is used in the Assembly, C, and other high-level languages we use.

In addition, the JDK original code is also often used >>, >>> operator,>> is signed shift, high fill sign bit, right shift;>>> is unsigned move, high 0, right shift.


For memory storage of data types, describe the following:

Native types, such as int i = 3, are stored in the stack regardless of the variable or value, and the class type, such as Integer i = 3, is stored in the stack, and the object is an object stored in the heap, since the integer is so, then integer a = 3,integer b = 3 , is a = = B, is it set up?

The answer is that this is because the JVM optimizes the base type, and when it is assigned to B, it looks for the existence of an integer object with a value of B, because it already exists, so the B = a assignment is done directly, that is, A and b all point to the same memory address, so a = = B is established.

So integer a = new Integer (3), Integer b = new Integer (3), A = = B is it true? Now because we are new, forcing the newly allocated memory, so a and b no longer point to the same memory address, so a = = B is not true, but A.equals (b) is established, because the primitive value of the integer object represented by a and B is the same.


String


String a = "abc", String b = "abc", as above for the explanation of integer, a = = B is established, the principle is the same.

For operations such as string s = a + B, each operation opens up a memory space in the heap, so the performance is low for a large number of character operations, so for a large number of character operations, the recommended StringBuffer and StringBuilder, Where StringBuffer is thread-safe, StringBuilder is a new addition to version 1.5 and is non-thread-safe.


Exceptions and Errors


Exception and error are inherited from Throwable objects, exception are divided into two categories, RuntimeException (runtime exception, unchecked) and general exception (checked), error is a serious error, also unchecked.

In a nutshell, checked must be handled with try/catch or throw, which can be recovered during execution, such as java.io.FileNotFoundException, while unchecked exceptions do not require try/catch processing. Like Java.lang.NullPointerException.

In the more popular languages, Java is the only language that supports checked exceptions, which requires that we have to deal with them, both pros and cons.

With regard to exception classes, error classes, there are many definitions in the JDK that describe the various types of errors that our code might encounter, not all of which are described here.


Runtime


There are many runtime environment-related classes in the Java.lang package that can be used to view various information about the runtime environment, such as memory, locks, security, garbage collection, and so on. See the following hook code, when the JVM shuts down, do some bad in the program calculation process of the resource release work, as follows:

public class Mongohook {static void Addclosehook () {runtime.getruntime (). Addshutdownhook (New Thread () {@Overridepublic void Run () {Mongodbconn.destoryallforhook ();}}) ;}}


Multithreading


Thread, Runnable, threadlocal, etc., for more on multithreading, you can refer to.


Interface


Clonable: Life-style interface

Comparable: Object comparison, generic class

Appendable:

Charsequence: A unified string read-only interface with 4 methods, Length (), CharAt (), subsequence (), toString ().

Readable:

Iterable: iterators


Annotation class


Mainly in the Java.lang.annotation package, the annotation class is defined by the @interface, the scope of the annotation class can be method, property, package, etc., the function can be the source, Runtime, class.

For example, override is an annotation class, used to mark the implementation of the interface defined in the class, its source code is as follows;

Package Java.lang;import java.lang.annotation.*; @Target (Elementtype.method) @Retention (Retentionpolicy.source) Public @interface Override {}


A brief analysis of JDK source code base Class library in--java.lang package

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.