Introduction to Java 6.0 New Features, Part–1

1) Introduction

This article covers the various new features of Java 6, also known as Mustang. This article assumes that readers have sufficient knowledge over the concepts and terminologies in Java 5.0. For more information on Java 5.0, readers can vist the resources available in javabeat here. Though there is no significant changes at the Language Level, though Mustang comes with a bunch of enhancements in the other areas like Core, XML and Desktop. Most of the features are applicable both to J2SE and J2EE Platforms.

also read:

2) Java 6 Features

A feature or an enhancement in Java is encapsulated in the form of a JSR. JSR, which stands for Java Specification Request is nothing but a formal proposal which details the need for a specific functionality to be available in the Java Platform that can be used by Applications. These JSR’s will be reviewed and released by a committee called Java Expert Groups (JEG). This article covers the following list of features (or JSRs’) that comes along with the Java 6 Platform.

  • Pluggable Annotation Processing API (JSR 269)
  • Common Annotations (JSR 250)
  • Java API for XML Based Web Services – 2.0 (JSR 224)
  • JAXB 2.0 (JSR 222)
  • Web Services Metadata (JSR 181)
  • Streaming API for XML (JSR 173)
  • XML Digital Signature (JSR 105)
  • Java Class File Specification Update (JSR 202)
  • Java Compiler API (JSR 199)
  • JDBC 4.0 (JSR 221)
  • Scripting in the Java Platform (JSR 223)

The JSRs’ that are covered in this article are Common Annotations, JDBC 4.0 and Scripting in the Java Platform. Rest of the JSRs’ will be covered in the subsequent article.

3) Common Annotations

The aim of having Common Annotations API in the Java Platform is to avoid applications defining their own Annotations which will result in having larger number of Duplicates. This JSR is targeted to cover Annotations both in the Standard as well the Enterprise Environments. The packages that contain the annotations are javax.annotation and . Let us discuss in brief the commonly used Annotations that are available in this JSR in the next subsequent sections.

3.1) @Generated Annotation

Not all the source files or the source code in an application is hand-written by Developers. With the increasing number of Tools and Frameworks, most of the common Boiler-Plate Code is generated by the Tools or the Frameworks itself if they have been properly instructed. Such Tool Generated Code can be marked with @Generated Annotation. Consider the following sample code snippet,

public class MyClass{

    public void developerCode(){

        value = "ClassNameThatGeneratedThisCode",
        comments = "This is Tool Generated Code",
        date = "5 June 2007"
    public void toolGeneratedCode(){


The value for the @Generated Annotation would be usually the class name that generated this code. Optionally, comments and date can be given to add more clarity to the generated code. Note this @Generated Annotation is not limited to a method definition, it can also be defined for Package Declaration, Class Declaration, Interface Declaration, Local Variable Declaration, Field Declaration, Parameter Declaration etc.

3.2) @Resource and @Resources Annotation

Any Class or Component that provides some useful functionality to an Application can be thought of as a Resource and the same can be marked with @Resource Annotation. This kind of Annotation can be seen normally in J2EE Components such as Servlets, EJB or JMS. For example consider the following code snippet,

@Resource(name = "MyQueue", type = javax.jms.Queue,
    shareable = false,
    authenticationType = Resource.AuthenticationType.CONTAINER,
    description = "A Test Queue"
private javax.jms.Queue myQueue;

Queue is a class available as part of JMS API and it serves as a target for Asynchronous Messages being sent by Applications. The various properties to note in @Resource Annotation are: ‘name’ which is the JNDI Name of this resource, ‘type’ which is the type of the resource which usually points to the Fully Qualified Class Name, ‘shareable’ which tells whether this resource can be shared by other components in the Application or not, ‘authenticationType’ which indicates the type of authentication to be performed either by the Container or by the Application and the Possible values are AuthenticationType.CONTAINER and
AuthenticationType.APPLICATION and ‘description’ which is a string that describes the purpose of this resource.
When the Application containing the @Resource Annotations are deployed to a Server, the Container will scan for all the Resource references during the time of Application loading and then will populate the @Resource References by assigning new instances.
@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines @Resources Annotation,
@Resources is nothing but a collection of @Resource entries. Following is a sample code that defines
@Resources Annotation,

    @Resource(name = "myQueue" type = javax.jms.Queue),
    @Resource(name = "myTopic" type = javax.jms.Topic),

3.3) @PostConstruct and @PreDestroy

J2EE Components are usually created by the Container or the Framework on which they are deployed. Container creates new components by calling the Default or the No Argument Constructor. It is a very common need that a component needs to get initialized with some default values after it has been created. @PostConstruct Annotation serves that purpose. It is a Method-Level Annotation, meaning that this Annotation can be applied only to a Method and it will be fired immediately as soon the Component is created by invoking the Constructor.
Consider the following set of code,

public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){

    public void loadDefaults(){

        // Load the Driver Class.
        // Get the Connection and Do other stuffs.


We can see that @PostConstruct Annotation is normally used to Initialize the Resources that are Context specific. The loadDefaults() method which is marked with @PostConstruct Annotation will be called immediately by the Container as soon as an instance of MyDbConnectionComponent is created. There are certain guidelines to be followed while defining the PostConstruct method such as: the method should not be marked as static, return type should be void, it cannot throw any CheckedExceptions etc.
The counterpart to @PostConstruct Annotation is the @PreDestroy Annotation. From the name of the Annotation itself, we can infer that the method that is marked with this Annotation will be called before an object is about to be removed or destroyed by the Container. Like the @PostConstruct Annotation, this is also a Method-Level Annotation and the following code snippet proves this,

public class MyDbConnectionComponent{

    public MyDbConnectionComponent(){

    public void releaseResources(){

        // Close the Connection.
        // Unload the Class Driver from the System


The method releaseResources() will be called by the Container before the object is about to be Destroyed. Resource releasing code are ideal candidates to be placed in the @PreDestroy Annotation method.

3.4) Role Based Annotations

The following sections discuss the various Role-based Annotations that are very common in Applications that are very concerned about Security. A Typical Application is accessed by a wide range of Users and Users themselves fall into Several Roles. Considering an IT Organization, all Employees fall into the General Category of Roles namely Admin, Director, Manager, Engineer, Programmer etc. It is very common to see Applications following Role-Based Security Model. The Annotations @DeclareRoles, @RolesAllowed, @PermitAll, @DenyAll and @RunAs are Role-Based Annotations and are covered here.

3.4.1) @DeclareRoles Annotations

This is a Class-Level Annotation meaning that this Annotation is applicable only to a Class Declaration. If applied to a Class or a Component, it essentially declares the valid Set of Roles that are available for this Component. Consider the following code which will clarify this,

@DeclareRoles(value = {"Director", "Manager", "Others" })
public class LeaveService{

    private Context context;

    public void applyLeave(){

        // Any employee can apply for leave. So no need for any
        // conditional check.

    public void grantLeave(){
            // Grant Leave.

    public void cancelLeave(){
            // Cancel Leave.

    private boolean checkUserInRole(){
        if( (context.isCallerInRole("Director") )
            || (context.isCallerinRole("Manager")) ){
            return true;

        return false;

In the above example, the component LeaveService has been marked with @DeclareRoles Annotations with Role Name values namely Director and Manager. It has three services namely: applying for leave (applyLeave()), granting for leave (grantLeave()) and cancellation of leave (cancelLeave()). It is acceptable that only Employees in the Superior Role (Director or Manager) can grant or deny leaves to their sub-ordinates. So additional conditional checks are done to ensure that whether the User who is accessing the grantLeave() or the cancelLeave() service belongs to either of the defined Roles(Director or Manager). Since any employee in a company can apply for a leave, (whose Role Name is given as Others), no conditional checks are done in applyLeave() method.

3.4.2) @RolesAllowed Annotation

This is a Class/Method Level Annotation which is used to grant access to some Service(s) to the defined set of Users who are mentioned by their Role Names in the Annotation. Let us get into the following example straightaway,

@DeclareRoles("A", "B", "C", "X", "Y", "Z")
@RolesAllowed("A", "B", "C")
public class MyServiceComponent{

    @RolesAllowed(value = {"A", "X", "Y"} )
    public void myService1(){

    @RolesAllowed(value = {"B", "Y", "Z"} )
    public void myService2(){

    @RolesAllowed(value = {"X", "Y", "Z"} )
    public void myService3(){

    public void myService4(){

The above code declares various roles namely “A”, “B”, “C”, “X”, “Y” and “Z” for the component MyServiceComponent. The @RolesAllowed Annotation when applied to a method grant Access to Users who are in that Roles only. For example, only Users with Roles “A” or “X” or “Y” are allowed to access the method myService1(). In the case of myService2(), “B”, “Y” or “Z” role Users are allowed to access it and so on.
What happens in the case of myService4()??
No @RolesAllowed is specified for this method. The fact is that, if a method doesn’t have @RolesAllowed Annotation attached to it, then it will inherit this property from the class where it has been defined. So, in our case, Users in the Role “A”, “B” or “C” can access the method myService4() becuase these set of Roles have been defined at the Class Level. What if the Class Declaration itself doesn’t have the @RolesAllowed Annotation declared? The answer is simple: it will take all the Roles that are defined in @DeclareRoles.

3.4.3) @PermitAll and @DenyAll Annotation

These are Class/Method Level Annotations and if applied to a Class Declaration will affect all the methods in the class, and when applied to a method will affect that method only.
Consider the following sample,

@DeclareRoles(value = {"A", "B", "C"} )
class MyClass{

    public void commonService(){

    public void confidentialService(){

From the above code, it is inferred that commonService() method can be accessible by all Users irrespective of their Roles as it is marked with @PermitAll() annotation and no one can access the confidentialService() because it has been marked with @DenyAll() annotation.

4) Scripting Language for the Java Platform

4.1) Introduction

Java 6 provides the Common Scripting Language Framework for integrating various Scripting Languages into the Java Platform. Most of the popular Scripting Languages like Java Script, PHP Script, Bean Shell Script and PNuts Script etc., can be seamlessly integrated with the Java Platform. Support for Intercommunication between Scripting Languages and Java Programs is possible now because of this. It means that Scripting Language Code can access the Set of Java Libraries and Java Programs can directly embed Scripting Code. Java Applications can also have options for Compiling and Executing Scripts which will lead to good performance, provided the Scripting Engine supports this feature. Let us have a high-level overview of this JSR before going in detail.
Following sections provide the two core components of the Scripting engine namely,

  • Language Bindings
  • The Scripting API

4.2) Language Bindings

The Language Bindings provides mechanisms for establishing communications between the Java Code and the Script Code. More specifically, it deals with how actually a Java Object creating by a Script Code is stored and maintained by the Scripting Engine, how the Script Arguments are converted back and forth, how the Calls that are made to the Java Methods from within the Scripting Code got translated and how the return values from the Java Code are made available to the Scripting code. To illustrate on this further, consider the JavaScript Code,

var aJavaString = new String("A Test String");

This piece of code essentially creates a new Java String object and assigns it to a JavaScript object called aJavaString which is of var type. As soon as the Rhino Script Engine (which is the Scripting Engine name for JavaScript) parses this Script Code, it has to create a new instance of String object and should store it somewhere. The place where Java Objects and Script objects are stored are referred to as Bindings in Java Scripting Terminology. Here, aJavaString acts as a Proxy Object for the real java.lang.String object.
Again consider the following code,

var aJavaString = new java.lang.String('A Test String');
var length = aJavaString.substring(7, 13);

So many Micro-Level Tasks are involved if we analyse the above piece of code carefully. They are listed as follows,

  1. Script Arguments are Converted to Java Arguments
  2. Java Method to be invoked is identified
  3. Logic is performed on the invoked Java Method
  4. Return Values, if any, are sent back to the Scripting Code

The first line indicates that a new instance of java.lang.String object is created and it is stored in a Java Script object called aJavaString. Here aJavaString acts as a Proxy Object for the original java.lang.String object. After that we can see that the arguments 7 and 13 are passed from the Script Code to the method String.substring(int,int). The Engine will now convert the arguments that are to be sent to the Java method by using the Default Script-Java Mappings which is very specific to every Script Engine. After that, the Scripting Engine must ensure the availability of the method String.substring(int,int) at the run-time by abundantly depending on the Java Reflection API. Now the method is invoked and the logic gets executed. The return values are then converted using the Java-Script Mappings as defined by the Script Engine and will get populated in the length JavaScript object.

4.3) Scripting API

This API allows Java Programs to take the full advantage of Directing Embedding Scripting Code into the Applications. It also provides a framework wherein New Scripting Engines can be easily plugged-in. The entire API is available in the javax.script package.
ScriptEngineManager class provides mechanisms for Searching and Adding Scripting Engines into the Java Platform. Convenient methods are available for Discovering Existing Scripting Engines. For example, the following code will iterate and will list down all the Script Engines that are available in the Java 6 Distribution.

List allFactories = ScriptEngineManager.getEngineFactories();

for(ScriptEngineFactory engineFactory : allFactories){
    System.out.println("Engine Name" + engineFactory.getEngineName());

The ScriptEngineFactory is the Factory Class for creating ScriptEngine objects. As such, two different ways are there to get instances of ScriptEngine classes. One way is to call the method ScriptEngineFactory.getScriptEngine(). The other direct way is to depend on the ScriptEngineManager itself to call getEngineByName().

// First Way
ScriptEngineFactory rhinoFactory = getScriptEngineFactory();
ScriptEngine rhinoEngine = rhinoFactory.getScriptEngine();

// Second Way
String name  = "javascript";
ScriptEngine rhinoEngine = ScriptEngineManager.getEngineByName(engineName);

Execution of scripts can be done by calling the ScriptEngine.eval(String) method.
Bindings as represented by javax.script.Bindings, provide key/name information to ScriptEngines. Two types of Binding Scopes are available, one is the Global Scope and the other is the Engine Scope. By default, the ScriptEngineManager manages some set of Default bindings, which can be obtained by making a call to ScriptManager.getBindings(). The Bindings that are obtained in this manner (i.e from ScriptEngineManager) are called Global Bindings. Following is the code to get a reference to the Global-Bindings object and to populate it with application-specific values.

Bindings globalBindings = scriptEngineManager.getBindings();
globalBindings.put("key1", "value1");
globalBindings.put("key2", "value2");

It is also possible to customize the Binding information on Engine-by-Engine basis. For example, to obtain Bindings that is very specific to a particular Engine, a call to ScriptEngine.getBindings() can be made. These Bindings that are obtained in this way are called Engine Bindings.

4.4) Sample Code

This following Sample Application demonstrates how to directly embed Scripting Code in Java Applications. Argument passing between the Java Code and the Script Code are illustrated in this Sample.

package test;

import javax.script.*;

public class ScriptTest{

    public static void main(String[] args){

            // Create an instance of the Scripting manager.
            ScriptEngineManager manager = new ScriptEngineManager();

            // Get the reference to the rhino scripting engine.
            ScriptEngine rhinoEngine = manager.getEngineByName("javascript");

            // Get the Binding object for this Engine.
            Bindings bindings =	rhinoEngine.getBindings(ScriptContext.ENGINE_SCOPE);

            // Put the input value to the Binding.
            bindings.put("strValue", "A Test String");

            // Populate the script code to be executed.
            StringBuilder scriptCode = new StringBuilder();
            scriptCode.append("var javaString = new java.lang.String(strValue);");
            scriptCode.append("var result = javaString.length();");

            // Evaluate the Script code.

            // Take the output value from the script, i.e from the Bindings.
            int strLength = (Integer)bindings.get("result");

            System.out.println("Length is " + strLength);
        }catch(Exception exception){

In the above code, a new instance of ScriptEngineManager is created in the very first line. Then, the Scripting Engine
that comes shipped with the Mustang, (i.e, Rhino Java Script Engine) is obtained by calling ScriptEngineManager.getEngineByName(“javascript”). Arguments are passed from and to the Java Code with the help of Bindings. The input string to be processed is added to the Bindings with the call to Bindings.put(“strValue”, “A Test String”). Notice how the input string is populated within the script code at run-time, var javaString = new java.lang.String(strValue). It means that at run-time the Script code becomes var javaString = new java.lang.String(‘A Test String’). Then the script is executed by calling the ScriptEngine.eval(String) method. The output which is the length of the input string is now in the Script variable called result. And as mentioned previously, since all the Script and the Java Objects will be maintained and controlled by the Bindings, it is possible to get the value of the Script object result directly by calling Bindings.get(“result”).

6) Conclusion

This article covered some of the new features available in Java 6. It started off with the JSR that aimed in defining the Common Set of Annotations that can be used by Application Programs. Each and every Annotation in this package is briefly explained and examples were given to make it more understandable. Then, the Common Scripting Language Framework for the Java Platform is given in depth discussion along with the concept of Bindings, Scripting API and with a Sample Program.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This

Share this post with your friends!