J2se 1.5 In a nutshell Chinese Version

Source: Internet
Author: User
J2se 1.5 In a nutshell Chinese Version
2004-03-22 CLICK: 104
J2se 1.5 In a nutshell Chinese Version
Article

[H2] j2se 1.5 In a nutshell [/H2]

--------------------------------------------------------------------------------

According to the Translator's note: the understanding of the new features in j2se 1.5 is not thorough enough, so some mistakes may be made in the translation. Please kindly advise me

--------------------------------------------------------------------------------

Calvin Austin
February 2004

Java 2 platform Standard Edition (j2se) 1.5 (codenamed "tiger") is an important change to the Java platform and language. Currently, j2se 1.5 contains 15 JSR requests, the corresponding JCP results in nearly 100 significant changes.

Seeing that this version has brought so many exciting changes, you may want to know where you should start. as with previous releases, all changes will have a clear list stored in "Release Notes Guide ". this article from the j2se development team will guide you through major changes, so that you can quickly grasp what j2se 1.5 can provide before going into the API documentation.

J2se 1.5 focuses on the following key topics:

Simple development of Development
Scalability and Performance
Monitoring and management capabilities monitoring and manageability
Desktop client

Some features are also very important, but they are irrelevant to these topics, so they are listed at the end of the article:

Other features: Miscellaneous features

Simplified development of Development
You may have seen some reports on new features in Java that make development easier. these features include generic categories, metadata, automatic packing, an enhanced for loop, enumeration type, static introduction, C language input and output, variable parameters, parallel tools and a simplified RMI interface generation.

JSR 201 includes four of the above language features: enhanced for loop, enumeration type, static import and automatic packing; JSR 175 describes the metadata function; JSR 14 details generic categories.

The default language used in the javac compiler is j2se1.4. this means that if you want to use any of these new language features, you must add a parameter-source 1.5 on the javac command line during compilation. (Translator's note: This is why many developers cannot use these new features after downloading this version .)

Metadata metadata
The metadata feature in j2se 1.5 provides the ability to connect and attach data to Java class, interface, method, and field. these additional data or annotations can be recognized by the javac compiler or other tools, stored in the class file according to the configuration, and can be found through the Java reflection API at runtime.

One of the main reasons for Adding metadata to the Java platform is that similar development and running tools can get a basic framework, which can reduce the extra effort required during coding and publishing. A tool can use this metadata to generate additional code or provide additional information during debugging.

Instead of the metadata tool, the following sample code creates a Metadata Annotation for intelligent debugging. this annotation will be displayed in subsequent debugging. we can see that most of the metadata tags constitute a standard, fixed set.

Import java. Lang. annotation .*;
Import java. Lang. Reflect .*;

@ Retention (Java. Lang. annotation. retentionpolicy. runtime) @ interface debug {
Boolean devbuild () default false;
Int counter ();
}

Public class initialize est {
Final Boolean production = true;
@ Debug (devbuild = production, counter = 1) Public void testmethod (){
}

Public static void main (string [] ARGs ){

Sorted est Mt = new sorted EST ();
Try {
Annotation [] A = Mt. getclass (). getmethod ("testmethod"). getannotations ();
For (INT I = 0; I <A. length; I ++ ){
System. Out. println ("A [" + I + "] =" + A [I] + "");
}
} Catch (nosuchmethodexception e ){
System. Out. println (E );
}
}
}

With metadata processing tools, many repeated encoding steps can be reduced to a simple metadata tag. For example, the remote interface service implementation needed to access the JAX-RPC can be implemented as follows:

Previously before

Public interface pingif extends remote {
Public void Ping () throws RemoteException;
}
Public class ping implements pingif {
Public void Ping (){
}
}

After metadata is used

Public class ping {
Public @ remote void Ping (){
}
}

Generic Type generic types
Generics have been expected in the Java Community for a long time. Now generics have become part of j2se 1.5. first, we can see that the generic category is in the Set API. the Set API provides some common functions, such as javaslists, arraylists, and hashmaps. the following example uses the j2se 1.4.2 class library and the default javac compiling mode.

Arraylist list = new arraylist ();
List. Add (0, new INTEGER (42 ));
Int Total = (integer) list. Get (0). intvalue ();

In the above example, the forced transformation from the last row to the integer type is the forced transformation problem that the generic category wants to solve. this problem is that the j2se 1.4.2 collection API uses objects to store collection objects, which means that this set cannot be detected during compilation. A typical problem is that classcastexception is thrown during runtime.

The example above is rewritten after generic categories are used:

Arraylist <integer> List = new arraylist <integer> ();
List. Add (0, new INTEGER (42 ));
Int Total = list. Get (0). intvalue ();

These generic set APIs must be used to specify the data types stored in the set during compilation. with generics, there will be no need for transformation, in this example, if you try to add a string type variable to the set declared as integer, a compilation error will occur.

Generic categories enable API designers to provide general functions and run on multiple data types, and check the security of types during compilation.

Generic APIs are a little more complex. We recommend that you start with the source code of the Java. util. Collection package and the API user guide.

Autoboxing and auto-unboxing of primitive types for Basic Types
Conversions between basic types and corresponding object replicas, such as converting from basic int, Boolean to their corresponding object replicas integer and Boolean will require unnecessary code, in particular, some conversion operations that only appear in the collection API.

The automatic packing and automatic unpacking of Java basic types make the code more concise and easy to understand. the following example shows how to store an int type of data to an arraylist and then extract it. j2se 1.5 Enables automatic conversion between int and integer objects.

Previously before

Arraylist <integer> List = new arraylist <integer> ();
List. Add (0, new INTEGER (42 ));
Int Total = (list. Get (0). intvalue ();

After using automatic packing and automatic unpacking

Arraylist <integer> List = new arraylist <integer> ();
List. Add (0, 42 );
Int Total = list. Get (0 );

Enhanced for loop enhanced for Loop
In the set API, The iterator class is a class with a very high usage. it provides the ability to access the elements of a set in sequence. the newly enhanced for loop can replace iterator when accessing collection elements in a simple sequence. the compiler automatically generates the necessary cyclic code with type security and does not require transformation operations.

Previously before

Arraylist <integer> List = new arraylist <integer> ();
For (iterator I = List. iterator (); I. hasnext ();){
Integer value = (integer) I. Next ();
}

After using the enhanced for loop

Arraylist <integer> List = new arraylist <integer> ();
For (integer I: List ){...}

Enumerated types
This type provides an enumerated type compared to a constant using static final. if you used variable names such as Enum in your code, you need to adjust your code when compiling with javac-source 1.5, because j2se 1.5 introduces a new keyword enum.

Public Enum stoplight {red, Amber, green };

Static Import
The static introduced feature is to use a statement such as "Import static" so that you can directly use static constants in a class without entering the class name. for example, we often use borderlayout when adding a control. after static introduction, you only need to call the center.

Import static java. AWT. borderlayout .*;
Getcontentpane (). Add (New jpanel (), center );

Formatted output formatted output
Developers can now use functions like printf in C language to produce formatted output. now you can use printf like in C, and the language is basically unchanged. Some formats may need to be slightly changed.

Most common C printf formats can be used, and some Java classes such as date and biginteger also have formatting rules. You can find more information in the Java. util. formatter class.

System. Out. printf ("name count/N ");
System. Out. printf ("% S % 5d/N", user, total );

Formatted input
This internal API provides basic data reading functions, such as reading data from the console or any other data streams. the following example reads a string from the standard input and expects the string to be followed by an int value.

Methods In begin, such as next and nextint, will automatically expire when there is no data. if you need to process a very complex input, you can also use Java. util. the pattern matching algorithm in the formatter class.

S = logging. Create (system. In );
String Param = S. Next ();
Int value = S. nextint ();
S. Close ();

Variable Parameter varargs
The variable parameter (varargs) function allows multiple variable parameters to be input in a method. and this is just simple to use... to indicate that a method accepts an indefinite parameter. this is the basis for accepting any number of parameters in the printf method.

Void argtest (object... ARGs ){
For (INT I = 0; I <args. length; I ++ ){
}
}

Argtest ("test", "data ");

Parallel tool concurrency utilities
The parallel toolkit was proposed by Doug Lea in a leading JSR-166 to be added to j2se 1.5, a very popular parallel toolkit. it provides a powerful, high-level thread constructor that includes executors, such as a thread task framework, thread-safe queues, timers, and locks (including atomic locks) and some other basic types of synchronization.

The lock is a well-known signal. A signal can be used in places where wait is currently used. It is usually used to restrict access to a code block. semaphores are more flexible and can be accessed by multiple parallel threads. They also allow you to test the lock before getting a lock. the following code demonstrates the use of a semaphore, also known as a binary signal. for more information, see Java. util. concurrent package.

Final private semaphore S = new semaphore (1, true );
S. acquireuninterruptibly (); // for non-blocking version use S. Acquire ()

Balance = balance + 10; // protected value
S. Release (); // return semaphore token

RMI compiler -- rmic -- the RMI Compiler
You may no longer need to use rmic to generate remote interface piles. the dynamic proxy method shows that the information provided by the pile can be found at runtime. for more information, see RMI release notes.

Scalability and Performance
The release of j2se 1.5 ensures improved scalability and performance, especially when the startup and memory are imprinted, allowing you to easily publish an application and run it very quickly.

A significant update is to introduce the sharing of class data in the hotspot JVM. this technology not only shares read-only data among multiple running JVMs, but also improves the startup time so that these classes are pre-loaded like the core classes of the JVM.

Performance ergonomics is a new feature in j2se 1.5, which means that if you have used special JVM runtime options in the past j2se version to improve performance, this will be worth reverifying your performance if you do not have any JVM runtime parameters or a small number of parameters in j2se JVM, because j2se performance has improved a lot.

Monitor and manage monitoring and manageability
Monitoring and management is a key component of RAS (reliability, availability, serviceability) on the Java platform.

JVM Monitoring and Management APIs (JSR-174) detail a set of very understandable JVM internal mechanisms that are monitored on a running JVM. this information is accessed through the JMX (JSR-003) message Bean and can be remotely accessed through the JMX remote interface (JSR-160) or through industry-standard SNMP tools.

One of the most important features is an underlying memory detector. when the entrance (threshold) is crossed, JMX mbeans can notify those registered listeners. For more information, see javax. management and Java. lang. management

In order to intuitively see how simple these APIs are, the following is an example of reporting the detailed usage of the memory stack in the hotspot JVM.

Import java. Lang. Management .*;
Import java. util .*;
Import javax. Management .*;
Public class memtest {
Public static void main (string ARGs []) {
List pools = managementfactory. getmemorypoolmbeans ();
For (listiterator I = pools. listiterator (); I. hasnext ();){
Memorypoolmbean P = (memorypoolmbean) I. Next ();
System. Out. println ("memory type =" + P. GetType () + "memory usage =" + P. getusage ());
}
}
}

New JVM shaping API (JSR-163) New JVM profiling API (JSR-163)
This release also included a very strong local integer API called jvmti. this API has been described in detail in jsr163 and comes from the need to improve the integer interface. in any case, jvmti wants to focus on access to all tools in the local process. in addition to shaping, it also includes monitoring, debugging, and a tool that may support multiple types of code analysis.

The implementation of these Apis includes a bytecode Testing Device mechanism, jplis (Java programming language instrumentation services-Java programming language testing equipment service ). this will allow the analysis tool to add additional shaping when necessary. the advantage of this technology is that it allows more focus analysis and limits conflicts between different integer tools running in the JVM. this test device can even be automatically generated at run time, just like the class file during class loading and preprocessing.

The following example creates a set of test device hooks that can load a modified class file from the disk. to run the following test, use Java-javaagent: mybci bcitest when starting JRE.

// File mybci. Java
Import java. Lang. instrument. instrumentation;

Public class mybci {
Private Static instrumentation instcopy;

Public static void premain (string options, instrumentation insT ){
Instcopy = inst;
}
Public static instrumentation getinstrumentation (){
Return instcopy;
}
}

// File bcitest. Java

Import java. NiO .*;
Import java. Io .*;
Import java. NiO. channels .*;
Import java. Lang. instrument .*;

Public class bcitest {
Public static void main (string [] ARGs ){
Try {
Originalclass MC = new originalclass ();
MC. Message ();

Filechannel fc = new fileinputstream (new file ("modified" + file. Separator + "originalclass. Class"). getchannel ();
Bytebuffer Buf = FC. Map (filechannel. mapmode. read_only, 0, (INT) FC. Size ());
Byte [] classbuffer = new byte [Buf. Capacity ()];
Buf. Get (classbuffer, 0, classbuffer. Length );
Mybci. getinstrumentation (). redefineclasses (New classdefinition [] {New classdefinition (MC. getclass (), classbuffer )});
MC. Message ();
} Catch (exception e ){}
}
}

// Originalclass. Java
// Compile in current directory
// Copy source to modified directory, change message and recompile

Public class originalclass {
Public void message (){
System. Out. println ("originalclass ");
}
}

Improved diagnostic capability improved diagnostic ability
It is useless to generate a stack trace when there is no console window. Now there are two new APIs, getstacktrace and thread. getallstacktraces, which provide the ability to make the information programmable.

Stacktraceelement E [] = thread. currentthread (). getstacktrace ();
For (INT I = 0; I <E. length; I ++ ){
System. Out. println (E [I]);
}
System. Out. println ("/N" + thread. getallstacktraces ());

Hotspot JVM includes a mechanism for handling fatal errors, allowing the JVM to run a user-supported script or program when it gives up. A debugging tool can also use hotspot JVM's Service proxy connector to connect to this suspended JVM or those core files.

-XX: onerror = "command"

-XX: onerror = "pmap % P"
-XX: onerror = "GDB % P"
Optional % P used as process ID

Desktop client
The Java Desktop client is still a key component of the Java platform. At the same time, this component has been greatly improved in j2se 1.5.

This beta release contains some earlier improvements to the startup time and memory footprint. not only has it changed fast, but swing tool also has a brand new interface style called Ocean.

Based on j2se 1.4.2, The GTK replaceable look and feel and Window XP look and feel are further improved.

Windows XP
Click to enlarge

Linux/RedHat
Click to enlarge

Linux and Solaris users only need to have the latest OpenGL driver and graphics card, so that java2d can get local hardware acceleration, which can significantly improve the display effect, you only need to add the following parameters at startup:

Java-dsun. java2d. OpenGL = true-jar java2d.

At the same time, a quick X11 toolkit, called xawt, is also included in the Linux release version. By default, this Toolkit is used. if you need to use the previous motif toolkit, you need to add the following system parameters at startup:

Java-dawt. Toolkit = sun. AWT. motif. mtoolkit-jar notepad. Jar

(The X11 toolkit is Sun. AWT. x11.xtoolkit)

The X11 toolkit also uses the xdnd protocol, so you can drag and drop simple components between Java and other applications, such as StarOffice or Mozilla.

Other new features: Miscellaneous features
XML Core XML support
J2se 1.5 introduces some modifications to the Core XML platform, including XML 1.1, namespace, and XML schema. there are also the sax 2.0.1, XSLT and quick xlstc compilers, as well as Dom Level 3 support.

In addition to the support features for Core XML, jwsdp (Java Web Services developer pack) will release the latest Web Services Standard: JAX-RPC & SAAJ (WSDL/soap), jaxb, jaxr for XML encryption, digital signatures, and registration.

Supplementary characters support supplementary character support
The 32-bit supplemental character support is carefully added to j2se 1.5, Which is a part supported for the transition to Unicode 4.0. the supplemented characters are encoded into a special pair of UTF16 values to generate different characters, or from the code perspective, the replaced pair of values is followed by a high UTF16 value followed by a low UTF16 value, which is obtained from a special UTF16 value range.

In layman's terms, when using a string or character sequence, the core api library will transparently process these supplementary characters for you. however, Java's Char data is still 16-bit. A few methods that use char as a parameter now have corresponding methods that can accept an int value, these methods can present new features. in particular, the character class adds methods like the following code to retrieve the current and subsequent characters to support these supplementary characters:

String u = "/ud840/udc08 ";
System. Out. println (U + "+" + U. Length ());
System. Out. println (character. ishighsurrogate (U. charat (0 )));
System. Out. println (INT) U. charat (1 ));
System. Out. println (INT) U. codepointat (0 ));

For more information, see the Unicode section in the character class.

JDBC rowsets
Two updates are supported for JDBC row sets. one is cachedrowset, which contains a set of rows stored in the memory and retrieved from the database. and they are not connected, which means that the updates to these row sets can be synchronized to the database after a period of time.

The other is webrowset, which uses XML to transmit row data information in the database.

Refer to references:
For new language features for simplified development, see: http://java.sun.com/features/2003/05/bloch_qa.html

JSR tiger component jsrs included in j2se Tiger
003 Java Management Extensions (JMX) specification http://jcp.org/en/jsr/detail? Id = 3

013 decimal arithmetic enhancement http://jcp.org/en/jsr/detail? Id = 13

014 add generic types to the Java programming language http://jcp.org/en/jsr/detail? Id = 14

Java SASL specification http://jcp.org/en/jsr/detail? Id = 28

114 JDBC rowset implementations http://jcp.org/en/jsr/detail? Id = 114

133 Java Memory Model and thread specification revision http://jcp.org/en/jsr/detail? Id = 133

160 Java Management Extensions (JMX) Remote API 1.0 http://jcp.org/en/jsr/detail? Id = 160

163 Java platform profiling architecture http://jcp.org/en/jsr/detail? Id = 163

166 concurrency utilities http://jcp.org/en/jsr/detail? Id = 166

174 Monitoring and Management Specification for the Java Virtual Machine http://jcp.org/en/jsr/detail? Id = 174

175 a metadata facility for the Java programming language http://jcp.org/en/jsr/detail? Id = 175

200 network transfer format for Java archives http://jcp.org/en/jsr/detail? Id = 200

201 extending the Java programming language with enumerations, autoboxing, enhanced for loops and static import http://jcp.org/en/jsr/detail? Id = 201

204 Unicode supplementary character support http://jcp.org/en/jsr/detail? Id = 204

206 Java API for XML Processing (JAXP) 1.3 http://jcp.org/en/jsr/detail? Id = 206

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.