J2SE 1.5 in a Nutshell Author: Calvin Austin

xiaoxiao2021-03-06  74

J2SE 1.5 in a nutshell

Java 2 Platform, Standard Edition (J2SE) version 1.5 ( "Tiger") is the next major revision to the Java platform and language; it is currently slated to contain 15 component JSRs with nearly 100 other significant updates developed through the Java Community Process ( JCP).

With so many exciting changes in this release, you may be wondering where you should start. As in previous releases, the comprehensive list of all changes is available in the Release notes guide. This article, from the J2SE team, will take you through the MAJOR CHANGES SO That You Have A Grasp of What J2se 1.5 Has To Offer, Before Diving Into The API DOCS.

The J2SE 1.5 Release IS Focused Along Certain Key Themes:

Ease of Development Scalability and Performance Monitoring and ManageAbility Desktop Client

There Are A Small Number of Features That Are Arejatly Fit in with the the the the the

Miscellaneous Features

Ease of development

You may have already seen reports about some of the new Java Language changes that comprise the Ease of Development theme. The changes include generic types, metadata, autoboxing, an enhanced for loop, enumerated types, static import, C style formatted input / output, Variable Arguments, Concurrency Utilities, And Simpler RMI Interface Generation.

JSR-201 Contains Four of these Language Changes; Enhanced for loop, enumerated and autoboxing; JSR-175 Specifies The New Metadata FunctionAlity, while JSR-14 Details Generic Types.

The New Default Language Specification Implement by The Javac Compiler Is Version 1.5, You Do Not Need To Supply The Option - Source 1.5 as Required in Beta1.

Metadata

The metadata feature in J2SE 1.5 provides the ability to associate additional data alongside Java classes, interfaces, methods, and fields. This additional data, or annotation, can be read by the javac compiler or other tools, and depending on configuration can also be stored in the class file and can be discovered at runtime using the Java reflection API.One of the primary reasons for adding metadata to the Java platform is to enable development and runtime tools to have a common infrastructure and so reduce the effort required for programming and deployment . A Tool Could Use The Metadata Information To Generate Additional Source Code, or To Provide Additional Information When Debugging.

In beta2 we are pleased to announce the availability of an annotation processing tool called apt. Apt includes a set of new reflective APIs and supporting infrastructure to process program annotations. The apt reflective APIs provide a build-time, source-based, read-only view of program structure which cleanly models the Java programming language's type system. First, apt runs annotation processors that can produce new source code and other files. Next, apt can cause compilation of both original and generated source files, easing development. For more information ON Apt Refer to the Apt Guide.

.

import java.lang.annotation *;. import java.lang.reflect *;. @Retention (java.lang.annotation.RetentionPolicy.RUNTIME) @interface debug {boolean devbuild () default false; int counter ();} public class MetaTest {final boolean production = true; @debug (devbuild = production, counter = 1) public void testMethod () {} public static void main (String [] args) {MetaTest mt = new MetaTest (); try {Annotation [] A = mt.getClass (). getMethod ("testmethod"). getanNotations (); for (int i = 0; i

BEFORE

PUBLIC Interface Pingif Extends Remote {Public Void Ping () THROWS RemoteExcext;} PUBLIC CLASS PING IMPLEments PING {Public Void Ping () {}}

After

Public class ping {public @Remote void ping () {}}

Generic Types

Generic types have been widely anticipated by the Java Community and are now part of J2SE 1.5. One of the first places to see generic types in action is the Collections API. The Collections API provides common functionality like LinkedLists, ArrayLists and HashMaps that can be used By next esample uses the 1.4.2 libraries and the default javac compile mode.Arraylist list = new arraylist (); list .add (0, new integer (42)); int total = ("in Integer ). ITIT (0)). INTVALUE ();

The cast to Integer on the last line is an example of the typecasting issues that generic types aim to prevent. The issue is that the 1.4.2 Collection API uses the Object class to store the Collection objects, which means that it can not pick up type Mismatches At Compile Time. The First NOTIFICATION OF A Problem is a classcastexception at runtime.

The Same Example with the generified collections library is Written As Follows:

ArrayList list = new arraylist (); list.add (0, new integer (42)); int total = list.get (0) .intValue ();

The user of a generified API has to simply declare the type used at compile type using the <> notation. No casts are needed and in this example trying to add a String object to an Integer typed collection would be caught at compile time.

GENERIC TYPES Therefore Enable An API Designer To Provide Common Functionality That Can Be Used with Multiple Data Types and Which Also Can Be Checked for Type Safety At Compile Time.

Designing Your OWN Generic Apis is a little more complex That SIMPLY THEM. TO GET Started Look at The Java.util.collection Source and Also The API Guide.

Autoboxing and auto-unboXING OF Primitive Types

Converting between primitive types, like int, boolean, and their equivalent Object-based counterparts like Integer and Boolean, can require unnecessary amounts of extra coding, especially if the conversion is only needed for a method call to the Collections API, for example.The autoboxing and auto-unboxing of Java primitives produces code that is more concise and easier to follow. In the next example an int is being stored and then retrieved from an ArrayList. The 1.5 version leaves the conversion required to transition to an Integer and back to The compiler.

BEFORE

ArrayList list = new arraylist (); list.add (0, new integer (42)); int total = (List.get (0)). IntValue ();

After

ArrayList list = new arraylist (); list.add (0, 42); int total = list.get (0);

ENHANCED for loop

The Iterator class is used heavily by the Collections API. It provides the mechanism to navigate sequentially through a Collection. The new enhanced for loop can replace the iterator when simply traversing through a Collection as follows. The compiler generates the looping code necessary and with generic Types no additional casting is required.

BEFORE

ArrayList list = new arraylist (); for (iTerator i = list.iterator (); I.hasNext ();) {integer value = (integer) i.next ();}

After

ArrayList List = new arraylist (); for (Integer i: list) {...}

ENUMERATED TYPES

This type provides enumerated type when compared to using static final constants. If you have previously used the identifier enum in your own application, you will need to adjust the source when compiling with javac -source 1.5.public enum StopLight {red, amber, green }

Static import

The static import feature, implemented as "import static", enables you to refer to static constants from a class without needing to inherit from it. Instead of BorderLayout.CENTER each time we add a component, we can simply refer to CENTER.

Import static java.awt.BorderLayout. *; getContentPane (). Add (new jPanel (), center;

Formatted Output

Developers now Have the Option Os Generate formatted Output. This Will Help Migrate Legacy C Applications, As The Same Text Layout Can Be Preserve. Little or No Change.

Most of the common C printf formatters are available, and in addition some Java classes like Date and BigInteger also have formatting rules. See the java.util.Formatter class for more information. Although the standard UNIX newline '/ n' character is accepted, For Cross-Platform Support of newlines the java% n is recommented.

System.out.printf ("name count% n"); system.out.printf ("% s% 5d% n", user, total);

Formatted INPUT

Input and expects a string origrue.

The Scanner methods like next and nextInt will block if no data is available. If you need to process more complex input, then there are also pattern-matching algorithms, available from the java.util.Formatter class.

Scanner s = new scanner (system.in); string param = snext (); int value = s neyxt (); s.close (); varargs

The varargs functionality allows multiple arguments to be passed as parameters to methods. It requires the simple ... notation for the method that accepts the argument list and is used to implement the flexible number of arguments required for printf.

Void Argtest (Object ... args) {for (int i = 0; i

Concurrency Utilities

The concurrency utility library, led by Doug Lea in JSR-166, is a special release of the popular concurrency package into the J2SE 1.5 platform. It provides powerful, high-level thread constructs, including executors, which are a thread task framework, thread SAFE Queues, Timers, Locks (Including Atomic Ones), And Other Synchronization Primitives.

One such lock is the well known semaphore. A semaphore can be used in the same way that wait is used now, to restrict access to a block of code. Semaphores are more flexible and can also allow a number of concurrent threads access, as well AS Allow You to Test a Lock Before Acquiring It. The Following Example Uses Just One Semaphore, Also Known As a binary semaphore. See the java.util.concurrent package for more information.

Final private semaphore s = new semaphore (1, true); s.acquireuninterruptibly (); // for non-blocking version use s.acquire () Try {balance = balance 10; // protected value} finally {s.release (); // returnis semaphore token}

RMIC - The RMI Compiler

You no longer need to use rmic, the rmi compiler tool, to generate most remote interface stubs. The introduction of dynamic proxies means that the information normally provided by the stubs can be discovered at runtime. See the RMI release notes for more information.Scalability And Performance

The 1.5 Release Promises Improvements in Scalability and Performance, With A New Emphasis On Startup Time and Memory Footprint, To Make It Easier To Deploy Applications Running At top speed.

One of the more significant updates is the introduction of class data sharing in the HotSpot JVM. This technology not only shares read-only data between multiple running JVMs, but also improves startup time, as core JVM classes are pre-packed.

Performance ergonomics are a new feature in J2SE 1.5. This means that if you have been using specialized JVM runtime options in previous releases, it may be worth re-validating your performance with no or minimal options.

Monitoring and manageability

Monitoring and ManageAbility IS A Key Component of Ras (Reliability, Availability, Serviceability) In The Java Platform.

The J2SE 1.5 release provides comprehensive monitoring and management support:. Instrumentation to observe the Java virtual machine, Java Management Extensions (JMX) framework, and remote access protocols All this is ready to be used out-of-the-box (See the. Management and monitoring release notes for more details.)

The JVM Monitoring & Management API specifies a comprehensive set of instrumentation of JVM internals to allow a running JVM to monitored. This information is accessed through JMX (JSR-003) MBeans and can accessed locally within the Java address space or remotely using the JMX remote interface (JSR-160) and through industry-standard SNMP tools.One of the most useful features is a low memory detector. JMX MBeans can notify registered listeners when the threshold is crossed, see javax.management and java.lang.management for details .

J2SE 1.5 provides an easy way to enable out-of-the-box remote management of JVM and an application (see Out-of-the-Box for details). For example, to start an application to be monitorable by jconsole in the same Local Machine, Use The Following System Property:

Java -dcom.sun.management.jmxremote -jar java2demo.jar

And to Monitor It Remotely Through JMX without Authentication:

Java -dcom.sun.management.jmxremote.port = 5001 -dcom.sun.management.jmxremote.ssl = false -dcom.sun.management.jmxremote.Authenticate = false -jar java2demo.jar

.

. Import java.lang.management *; import java.util *; public class MemTest {public static void main (String args []) {List pools = ManagementFactory.getMemoryPoolMXBeans (); for. (MemoryPoolMXBean p: pools) {System.out.println ("Memory Type =" P.gettype () "Memory USAGE =" P.getusage ());}}}

New JVM Profiling API (JSR-163)

The release also contains a more powerful native profiling API called JVMTI. This API has been specified through JSR-163 and was motivated by the need for an improved profiling interface. However, JVMTI is intended to cover the full range of native in-process tools access, which in addition to profiling, includes monitoring, debugging and a potentially wide variety of other code analysis tools.The implementation includes a mechanism for bytecode instrumentation, Java Programming Language Instrumentation Services (JPLIS). This enables analysis tools to add additional profiling only where it is needed. The advantage of this technique is that it allows more focused analysis and limits the interference of the profiling tools on the running JVM. The instrumentation can even be dynamically generated at runtime, as well as at class loading time, and pre -processed as class files.

The Following Example Creates An Instrumentation Hook That Can Load A Modified Version of The Class File from Disk. To Run this Test, Start The Jre with Java-JavaAgent: MyBCI Bcitest

// 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 () {System.out.Println ("OriginalClass");}}}}}

GENERATINGTASTACKTRACES PROVIDE THISTACKTRACES PROVIDE THREAD.GETALLSTACKTRACE.

StackTraceElement E [] = thread.currentthread (). GetStackTrace (); for (int i = 0; i

-Xx: OneRror = "Command" -xx: OneRror = "PMAP% P" -xx: OneRror = "GDB% P" optional% P Used As Process ID

Desktop Client

The Java Desktop Client Remains a Key Component of The Java Platform and as Such Has Been The Focus of Many Improvements in J2SE 1.5.

This Beta release contains some of the early improvements in startup time and memory footprint. Not only is the release faster, but the Swing toolkit enjoys a fresh new theme called Ocean. And by building on the updates in J2SE 1.4.2, there are further Improvements in the GTK SKINNABLE LOOK AND Feel and fel.

Windows XPClick to Enlarge

Linux / RedHatclick to enlarge

Linux and Solaris Uses, And New IN Beta2, Windows Uses, WHO Have the Latest OpenGL Drivers and SELECT Graphic Cards Can Get Native Hardware Acceleration from Java2d Using The Following Runtime Property:

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

THE Linux Release Also Has The Fast X11 Toolkit, Called Xawt, Enabled by Default. If You NEED TO Compare Against The Motif Version You Can Use The Following System Property:

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

(The x11 Toolkit Is Called Sun.awt.x11.xtoolkit)

The x11 Toolkit Also Uses The xdnd protocol so you can Drag-and-drop simple component bagween java and other application like staroffice or mozilla.miscellaneous Features

Core XML Support

.

In addition to the core XML support, future versions of the Java Web Services Developer Pack will deliver the latest web services standards: JAX-RPC & SAAJ (WSDL / SOAP), JAXB, XML Encryption, and Digital Signature and JAXR for registries.

Supplementary Character Support

32-bit supplementary character support has been carefully added to the platform as part of the transition to Unicode 4.0 support. Supplementary characters are encoded as a special pair of UTF16 values ​​to generate a different character, or codepoint. A surrogate pair is a combination of A high utf16 value and a following low utf16 value. The High and low value of utf16 values.

In general, when using a String or sequence of characters, the core API libraries will transparently handle the new supplementary characters for you. However, as the Java "char" still remains at 16 bits, the very few methods that used char as an argument . now have complementary methods that can accept an int value which can represent the new larger values ​​The Character class in particular has additional methods to retrieve the current character and the following character in order to retrieve the supplementary codepoint value as below:

String u = "/ ud840 / udc08"; system.out.println (u " " u.length ()); system.out.println (u.sterat (0)); system.out .println ((int) u.Charat (1)); system.out.println ((int) u.codepointat (0)); See the Unicode Section In Character for more details.

JDBC Rowsets

There are five new JDBC RowSet class implementations in this release. Two of the most valuable ones are CachedRowSet and WebRowSet. RowSet objects, unlike ResultSet objects, can operate without always being connected to a database or other data source. Without the expensive overhead of maintaining a connection to a data source, they are much more lightweight than a ResultSet object. The CachedRowSet contains an in-memory collection of rows retrieved from the database that can, if needed, be synchronized at a later point in time. The WebRowSet implementation, In addition, Can Write and read the rowset in xml format.

The Following Code Fragment Shows How Easy It Is To create and use a webrowset object.

Class.forName ( "org.postgresql.Driver"); WebRowSetImpl wrs = new WebRowSetImpl (); wrs.setCommand ( "SELECT COF_NAME, TOTAL FROM COFFEES"); wrs.setUsername ( "postgres"); wrs.setPassword ( "" ); WRS.SETURL ("JDBC: PostgreSQL: Test"); Wrs.execute (); // Executes Command and Populates WebSet All coffees wrs.absolute (// Moves Cursor to the first row of wrs.updateint (2, 10); // Reset Total Field to 10 Wrs.Updaterow (); // Finishes Edits To this Row Wrs.acceptchange (); // Writes New Total To The Data Source Wrs.WriteXML (System.out); // Also Exports Rowset in Xml Format WRS.Close (); References

NEW LANGUAGE FEATURES for Ease Of Development In The Java 2 Platform, Standard Edition 1.5: http://java.sun.com/features/2003/05/bloch_qa.html

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

New Post(0)