J2SE 1.5 in a nutshell Chinese version

xiaoxiao2021-03-06  106

J2SE 1.5 in a nutshell Chinese 2004-03-22 Click: 104

J2SE 1.5 in a nutshell Chinese version

Article

[H2] J2SE 1.5 in a nutshell [/ h2]

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

The translator is pressed by:

tell me

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

Calvin austin

February 2004

Java2 Platform Standard Edition (J2SE) 1.5 version (Code "Tiger") is the next important modification of the Java platform and language; currently 1.5 version of J2SE contains 15 JSR requests, corresponding JCP results in nearly 100 significant modify.

Seeing this version brings so exciting changes, you may want to know where you should start. Like previous release, all changes will have a clear list to save in "Release Notes Guide". This comes from this The J2SE development team will lead you to patrol the main changes, so that you can quickly grasp J2SE 1.5 quickly before the API documentation.

The J2SE 1.5 version will focus on the following key topics:

Easy development ease of development

Scalability and Performance Scalability and Performance

Monitoring and management capabilities Monitoring and ManageAbility

Desktop Client Desktop Client

There are also some features that are also important, but they are not related to these topics, so they are listed in the end:

Other Features Miscellaneous Features

Easy developed Ease of Development

You may have seen some reports on new features on Java language that make it easier to develop more simple. These features include generic categories, metadata, automatic packing, an enhanced for loop, enumeration type, static introduction, C language style input output, variable parameters, parallel tools, and a simple RMI interface generation.

JSR 201 includes 4 of the above language characteristics: enhanced For loops, enumeration types, static import and automatic packing; JSR 175 illustrates metadata function; while JSR 14 details the generic category.

The default language used in the Javac compiler is J2se 1.4. This means that if you want to use any of these new language features, you must add a parameter on the Javac's command line when compiled - Source 1.5. (Translator Press: This is also a lot of developers who have downloaded this version after discovering this new feature.)

Metadata Metadata

The metadata characteristics in J2SE 1.5 provide an ability to connect additional data into Java Class, Interface, Method, and Field. These additional data or annotations can be identified by the Javac compiler or other tools, and can be saved in Class according to the configuration In the file, you can discover the REFLECTION API of Java at runtime.

One main reason for adding metadata to the Java platform is that development and running tools can get a foundation framework that reduces additional efforts to be required when coding and publishing. One tool can use these metadata information to generate additional additional Code or provide additional information when debugging.

Instead of the metadata tool, the following sample code creates an intelligent debug metadata annotation. This annotation will be simply displayed in subsequent debugging. We can see that most metadata tags make up a standard, fixed set.

Import java.lang.annotation. *;

Import java.lang.reflect. *;

@Retention (java.lang.annotation.RuntionPolicy.Runtime) @Interface debug {

Boolean Devbuild () Default False;

Int counter ();

Public class metatest {

Final Boolean Production = True;

@Debug (devbuild = production, counter = 1) public void testHod () {

}

Public static void main (String [] args) {

Metatest MT = New metatest ();

Try {

ANNOTATION [] a = mt.getClass (). GetMethod ("testmethod"). GetAnNotations ();

For (int i = 0; i

System.out.println ("a [" i "] =" a [i] "");

}

} catch (nosuchmethodexception e) {

System.out.println (e);

}

}

}

With metadata processing tools, many duplicate encoding steps can be reduced into a simple metadata tab. For example, the remote interface service implementation required when accessing JAX-RPC can be implemented below:

Previous Before

Public interface pingif extends remote {

Public void ping () throws receexception;

}

Public Class Ping Implements pingif {

Public void ping () {

}

}

After using metadata after the AFTER

PUBLIC CLASSI

Public @Remote void ping () {

}

}

Pan type generic types

The generic category has already been expected in the Java community, and now generic is part of J2SE 1.5. The first significant can see the generic class is a collection of API. Collection API provides some general features, for example: LINKEDLISTS, ARRAYLISTS, and Hashmaps, etc. These can be used in a variety of set types. The following example uses J2SE 1.4.2 class libraries and uses the default Javac compile mode.

ArrayList List = New ArrayList ();

List.Add (0, New Integer (42));

INT TOTAL = ((Integer) list (0)). INTVALUE ();

The last line in the above example is a forced transformation to the integer type is a mandatory transformation problem that the generic category wants to solve. This problem is the collection of J2SE 1.4.2's collection API to store a collection object with Object, which means that this collection cannot be compiled. The type does not match the problem when detecting the type. A typical question is to throw ClassCastException at runtime.

Below is an example of rewriting after using the generic category:

ArrayList list = new arraylist ();

List.Add (0, New Integer (42));

INT TOTAL = list.get (0) .intValue ();

These generic collection APIs are forcibly specifying the data type stored in the collection time. After using a generic, there is no need for transformation, and if you try to add a String type if you try to add a string type Variables will lead to a collection error in the collection of INTEGER.

The generic category allows the API designer to provide generic functions and can be used in a variety of data types and can check the security of the type when compiling.

The generic API is slightly more complicated. It is recommended to start from the source code of the Java.util.Collection package and the API's usage guide.

Basic types of automatic packing and auto-unpacking Autoboxing and auto-unboXING OF Primitive Types transformation between basic types and corresponding object copies, such as the transformation of object copy INTEGER and Boolean from basic int, Boolean to them There will be some unnecessary code, especially some conversion operations that only in the collection API.

For Java basic types of automatic packing and automatic unpacking makes the code more simple and easy. The following example demonstrates storage of an int type into an ArrayList and take it out. J2se 1.5 makes it in int and integer The conversion between the objects can be carried out.

Previous Before

ArrayList list = new arraylist ();

List.Add (0, New Integer (42));

INT TOTAL = (List.get (0)). INTVALUE ();

Use the automatic packing and automatic unpacking After

ArrayList list = new arraylist ();

List.add (0, 42);

INT TOTAL = list.get (0);

Enhanced for loop ENHANCED for loop

In a collection of APIs, the Iterator category is a class of use rates. He provides the ability to access set elements in order. New enhanced for loops can replace the ITerator. Compiler will be used in simple order. Automatically generate the necessary belt types, and does not require loop code for transforming operations.

Previous Before

ArrayList list = new arraylist ();

Iterator i = list.iterator (); i.hasnext ();) {

Integer value = (integer) i.next ();

}

After using enhances for loops after AFTER

ArrayList list = new arraylist ();

Integer i: list) {...}

Enumered type ENUMERATED TYPES

This type is provided with enamel type than the constant used to use Static Final. If you have used the variable name like enum in your code, you will need to adjust you when you use Javac-Source 1.5. The code, because J2SE 1.5 introduces a new keyword ENUM.

Public enum stoplight {red, amber, green};

Static introduction static import

The static introduction features use the statement such as "Import Static" so that you can use the static constants in a class without entering the class name. For example, we often use the borderLayout.center used when adding a control, uses static introduction After you only need to simply call Center.

Import static java.awt.BorderLayout. *;

GetContentPane (). add (new jPanel (), center;

Formatted Output Formatted Output

Developers can now use features like the Printf in the C language to generate formatted outputs. You can now use Printf as in the C language, and the language is basically not changed, which is generally constant, some formats may require a slight change. a bit.

Most of the general-purpose C printf formats can be used, and some Java class, such as Date and Biginteger have formatted 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 formatted input INPUT

This Scanner API provides basic read data, such as the function of reading data from the console or any other data stream. The following example reads a string from the standard input and hopes that the string is then An INT value.

Methods in Scanner, for example, NEXT and NEXTIT are automatically invalid when there is no data. If you need to handle a very complicated input, you can also use the pattern matching algorithm in the Java.util.formatter class.

Scanner s = scanner.create (system.in);

String param = s.next ();

INT value = S.NEXTINT ();

s.close ();

Unexpected parameter varargs

Unscan parameters (VARARGS) functions allow for incorporation of unusual number of parameters in a method. This is just a simple need to use ... to indicate a method to accept uncertain parameters. And this is in the printf method to accept any number The basis of the parameters.

Void Argtest (Object ... args) {

For (int i = 0; i

}

}

Argtest ("Test", "DATA");

Parallel Tool Concurrency Utilities

The parallel toolkit is made by Doug LEA in JSR-166, which is proposed to J2SE 1.5, which is a very popular parallel tool package. He offers powerful, high-level thread constructor, including Actuator, such as a thread task frame, thread secure queue, timer, lock (containing atomic level lock) and other basic types of synchronization.

The lock is a well-known signal. A signal can be used in places where Wait is now used, and he is usually used to limit access to a code block. The amount of semina will be more flexible and allow multiple parallel threads to access, also Allows you to test this lock before getting a lock. The following code demonstrates the use of a semaphore, also known as two-point signals. For more information, please refer to the 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 RMIC - The RMI Compiler

You may never need to use RMIC to generate those remote interface piles. Methods of dynamic agents illustrate information that is usually provided by piles can be found at runtime. For more information, see RMI Release Notes.

Scalability and Performance Scalability and Performance

J2SE 1.5 release guarantees improving scalability and performance, especially when starting and memory imprint, making it easier to publish an application and run very fast.

A very significant update is to introduce the sharing of class data in the HotSpot JVM. This technology not only shares read-only data between multiple running JVMs, but also improves the startup time, making it looks like the core of the JVM. The same is preloaded.

Performance ergonomics is a new feature in J2SE 1.5, which means that if you use special JVM runtime options in the past J2SE version to improve performance, this will deserve that there is no JVM run in J2SE's JVM. Without parameters or small parameters, you re-verify your performance, because J2SE's performance has been improved.

Monitoring and Management Monitoring and ManageAbility

Monitoring and Management is a key component of RAS (RELIABILITY, AVAILABILITY, serviceABILITY) on the Java platform.

JVM's monitoring and management API (JSR-174) Detailed description of the JVM internal mechanism that is very easy to understand, these internal mechanisms are monitored on a running JVM. This information is passed through JMX (JSR-003) message bean Accessing, and can access remote access through JMX remote interface (JSR-160) or accessed through the industry standard SNMP tool. One of the most important features is a bottom memory detector. When Threshold crossed Time, JMX MBeans can inform those registered listeners, please refer to Javax.Management and Java.lang.Management

In order to visually see how simple is to use these APIs, there is an example of a detailed use of 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 = management.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 Plastic API (JSR-163) NEW JVM Profiling API (JSR-163)

This release also includes a very strong local shaping API called JVMTI. This set of APIs have been described in detail in JSR163, and is for the demand for improving the shaping interface. No matter how, JVMTI wants to pay attention to all local processes Tools in the inside. In addition to shaping, monitoring, debugging, and tools that may support multiple code analysis.

These APIs include a mechanism for a BYTECode test device, JPLIS (Java Programming Language Instrumentation Services-Java Programming Language Testing Device Service). This will allow the analysis tool to add additional plasticity when necessary. This technology is He allows more focus analysis and limits the conflicts between different plastic tools running in the JVM. This test device can even generate at runtime, just like the Class files with the Class of the pre-processed Class files.

The following example establishes a set of test equipment hooks that can be loaded from the disk. To run the following test, use Java -JavaAgent: MyBCI Bcitest mode when starting JRE.

// file mybci.java

Import java.lang.instrument.instrument;

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 (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 Ability Improved Diagnostic Ability

Generating stack tracking when there is no console window. There are now two new APIs, GetStackTrace, and Thread.GetallStackTraces provide the ability to program these information.

StackTraceElement E [] = thread.currentthread (). GetStackTrace ();

For (int i = 0; i

System.out.println (e [i]);

}

System.out.println ("/ N" thread.GetallStackTraces ());

HotSpot JVM includes a fatal error process mechanism that runs a user-supported script or a program when the JVM is abandoned. A debugging tool can also be connected to this already hanging JVM with the HOTSPOT JVM. Those core documents.

-Xx: OneRror = "Command"

-Xx: OneRror = "PMAP% P"

-Xx: OneRror = "GDB% P"

Optional% P Used as Process ID

Desktop Client Desktop Client

Java's desktop client is still a key component as a Java platform, and this component has also improved in J2SE 1.5.

In this beta release, there is some improvement in the startup time and memory imprint. Not only the fast, and the SWING tool also has a new interface style called Ocean.

On the basis of J2SE 1.4.2, there is further improved Look and Feel for GTK replaceable Look and Feel.

Windows XP

Click to enlarge

Linux / redhat

Click to enlarge

User of Linux and Solaris as long as there is the latest OpenGL driver and graphics card, you can get Java2D to get local hardware acceleration, which can improve the display effect, just add the following parameters when starting, you can add the following parameters:

Java -dsun.java2d.opengl = true -jar java2d. At the same time, in the release version of Linux also contains a fast X11 toolkit called XAWT, the default is to use this toolkit. If you need to use the past MotiF tool Package, you need to add the following system parameters when starting:

Java -dawt.toolkit = sun.awt.motif.mtoolkit -jar notepad.jar

(X11's toolkit is called Sun.awt.x11.xtoolkit)

At the same time, the X11 toolkit also uses XDND protocols, so you can drag simple components between Java and other applications, such as StarOffice or Mozilla, dragging and dropping.

Some new features Miscellaneous Features

Core support XML Core XML Support

J2se 1.5 introduces some modifications to the core XML platform, including XML 1.1, Namespace, XML Schema. There are SAX 2.0.1, XSLT, and fast XLSTC compilers, as well as support for Dom Level 3.

In addition to the support features of core XML, JWSDP (Java Web Services Developer Pack) will release the latest Web Services standard: JAX-RPC & Saaj (WSDL / SOAP), JAXB, XML encryption, and digital signature and registered JAXR.

Supplemental characters Support Supplementary CHARACTER Support

32-bit supplemental character support is a very careful addition to J2SE 1.5, he is a part as a transition to Unicode 4.0 support. Supplemental characters are encoded into a special pair of UTF16 values ​​to generate one different Character, or from the point of view, the one-pair of values ​​replaced by a high-level UTF16 value follows a low UTF16 value, and this high and low value is from a special UTF16 value range from.

Popular point says that when using a string or character sequence, the core API library will handle these supplement characters. But Java's char type data is still 16-bit, and a few ways to use char as a parameter. The corresponding way to accept an int value, these methods can express these big values. In particular, the CHARACTER class adds some methods in the following code to retrieve the current characters and subsequent characters to support these supplements. character:

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, please refer to the Unicode section in the Character class.

JDBC Row JDBC Rowset

There are two updates on the support of JDBC rows. One is a cachedrowset that contains a collection of rows that are saved from the database from the database. And they are not connected, which means that the update to these rows can be Synchronize to the database after a while.

The other is WebrowSet, is a row data information in the database with XML.

Refer to References:

For new language features for simplified development: http://java.sun.com/features/2003/05/bloch_qa.html

JSR Tiger Component JSRS included in this version of 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 type to the java programming language http://jcp.org/en/jsr/detail?id=14028 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

转载请注明原文地址:https://www.9cbs.com/read-124503.html

New Post(0)