What’s new in J2SE 5.0? Part 3: MetaData / Annotations and Enumerated Types
In the first two parts of this series of articles, we had a look at generics, enhanced for loop and auto boxing/ unboxing. In this final article in this series, we will look at metadata and annotations. What’s new in J2SE 5.0? Part 3: MetaData / Annotations and Enumerated Types
Three part series: What’s new in J2SE 5.0?:
- Part 1: Generics
- Part 2: Enhanced For Loop and Auto-boxing / Unboxing
- Part 3: MetaData / Annotations and Enumerated Types
What’s new in J2SE 5.0?- Part 3
MetaData / Annotations
Today, annotations and metadata are the buzzwords in the world of Java. J2SE 5.0 has brought this feature for us. In simple words metadata means data about data.
Javadoc comments are widely used to document the code. Then, why are annotations required?
Annotations go well beyond what Javadoc is capable of and achieve compile-time checking and analysis of Java code. This means we can perform many checks on compile-time itself, significantly reducing the debugging time spent trying to fix runtime errors.. For example, we override methods form the super class. And by using @Override annotation the information about method overriding is provided.
Annotations can be categorized as follows:
- Marker annotations: These annotations do not use any additional data. So no variables are used and just name is used.
- Single-value annotations: In this case, data supplied is just one argument or a single data member.
- Full annotations: More than one data elements are used by these types of annotations.
Listing 1 shows how the annotations are declared.
Listing 1
public class MyAnnotate {
@Override
public String toSring() {
return super.toString() + " Annotation Override";
}
}
In Listing 1 the annotation @Override has been used… Override is an in-built annotation provided with J2SE 5.0. We will use this annotation as an example.
- Now let?s see how annotations help us in providing data/information about our code and how at compile-time the code is checked with the help of annotations.
Listing 2
Compiling 1 source file to C: JavaApplication1buildclasses
C:JavaApplication1srcjavaapplication1MyAnnotate.java:3: method does not override a method from its superclass
@Override
1 error
BUILD FAILED (total time: 1 minute 11 seconds)
When we define the override annotation and compile, we get an error as shown in Listing 2. This error clearly states that the method we are trying to override doesn?t exist in the super class. Thus this annotation notifies that the method, which is annotated, is actually overriding the method from superclass. This annotation is used on methods and not on classes, interfaces or package declarations.
In J2SE 5.0 one more built-in annotation Deprecated have been provided. You can also define your own custom annotations.
{mospagebreak title=Enumerated Types}
Enumerated Types
This is the a nice feature introduced in J2SE 5.0. People who have worked with C, C++ would be happy to see enums appear in Java.. First, have a look at how was Java previously without enums.
Listing 5
public class MyEnum {
public static final int ENUM1 = 1;
public static final int ENUM2 = 2;
public static final int ENUM3 = 3;
public static final int ENUM4 = 4;
}
Listing 5 shows the hows the constants were used to be defined and to use them as enums. What has been done here is that static final constants of type int have been defined in class MyEnum. Now let?s see the problems with this traditional approach.
- As we see the defined fields are just ints. And there can be other int constants, which can be used or passed to the method.
So if we are doing something depending upon the constant supplied from MyEnum to the method, and somewhere some other int variable or value is supplied then entire thing fails. This shows that just defining the static final int constants is not type-safe. Then to work this perfectly a programmer has to check for that if the supplied int matches any constant defined in MyEnum or not. If not then check the conditions for the data supplied.
This involves a lot of work and is not error free and doesn?t assure type-safety.
Listing 6
public enum MyEnum { ENUM1 , ENUM2 , ENUM3 , ENUM4 };
Listing 6 shows us the new way of defining enums. Thus the allowed values can be specifically defined when creating an enumerated type. This ensures type-safety and no interference of other elements. And the constants/values defined enum can be used whenever the enum is instantiated. We can iterate over an enumerated type and access the values. We just have to use enhanced for. Listing 7
for(MyEnum me : MyEnum.values())
{System.out.println(?Value from enum = ? + me);
}
Similarly, enum can be used in switch statement also.
for(MyEnum me : MyEnum.values())
{switch(me)
{case ENUM1:
System.out.println("ENUM1");
break;
case ENUM2:
System.out.println("ENUM2");
break;
case ENUM3:
System.out.println("ENUM3");
break;
case ENUM4:
System.out.println("ENUM4");
break;
case ENUM5:
System.out.println("ENUM5");
break;}
}
In the above example if we run the code without adding case Enum5 then output will be as follows:
ENUM1
ENUM2
ENUM3
ENUM4
Now, if the case Enum5 is added then the output will be
MyClass.java:23: unqualified enumeration constant name required case ENUM5:
This is called as compile-time type safety. Not allowing the element which is not defined in MyEnum. I hope all the C/C++ lovers will have a relief when seeing the enum introduced in J2SE 5.0. Pure Java developers might not like enums that much and might take some time to understand and get used to this new concept. Let?s move on to Varargs and Static Imports.
{mospagebreak title=Varargs}
Varargs
Varargs means variable number of arguments or multiple arguments can be passed to the method.
Listing 8
void myMethod (MyObject … myobjects) {
for(MyObject myobj : myobjects) {
System.out.println(?MyObject = ? + myobj.hashCode());
}
}
In Listing 8 we see the notation MyObject ? This indicates that to myMethod no. of MyObject parameters can be passed. And resulting into the iteration can be performed on it to access the elements.
{mospagebreak title=Static Imports}
Static Imports
With static imports one can import/access the static members from classes/interfaces.
Listing 9
public interface MyInterface {
public static int mynum1 = 10;
public static int mynum2 = 20;
}
public class MyClass {
public static void main(String args[]) {
System.out.println(MyInterface.mynum1);
}
}
In Listing 9 when the variable mynum1 has been accessed in class MyClass, the qualifier name used is MyInterface. Listing 10 import static com.mypackage.MyInterface.*;
public class MyClass {
public static void main(String args[]) {
System.out.println(mynum1);
}
}
Listing 10 shows that mynum1 has been accessed without defining the qualifier name. Because it MyInterface is imported. But I feel there is one problem with static imports. In real life one has to import hundreds of interfaces. And not necessarily the variable names should be different in each interface. So if the variable mynum1 is defined in two interfaces and both the interfaces have been imported then it will cause a problem. Let?s look at Listing 11.
Listing 11
public interface MyInterface {
public static int mynum1 = 10;
public static int mynum2 = 20;
}
public interface YourInterface {
public static int mynum1 = 1234;
}
import static com.mypackage.MyInterface.*;
import static com.mypackage. YourInterface .* ;
public class MyClass {
public static void main(String[] args) {
System.out.println(mynum1);
}
In this case the following error will be thrown at compile-time.
Compiling 1 source file to C:JavaApplication1buildclasses
MyImports.java:8: reference to ONE is ambiguous, both variable ONE in javaapplication1.MyInterface and variable ONE in javaapplication1.YourInterface match
System.out.println(ONE);
1 error
BUILD FAILED (total time: 2 seconds)
Conclusion
In this 3 part series, I have looked at some main features as Metadata, Enumeration, Generics and Enhanced for. So I think all people now will start using J2SE 5.0 and will explore more and more features.
Author:
{mosimage}Chinmay Ogale can be reached at (chinmayogale AT gmail)
OK, so let me get this straight. A guy from a company which has conspicuously failed to make any money off of Java despite inventing it and owning the Java brand criticizes the business model of open source companies like JBoss which are being conspicuously successful at making money off of Java. And we are supposed to rethink something??