10/31/2006

Custom String Values for Enum

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

public enum MyType {
ONE {
public String toString() {
return "this is one";
}
},

TWO {
public String toString() {
return "this is two";
}
}
}
Running the following test code will produce this:
public class EnumTest {
public static void main(String[] args) {
System.out.println(MyType.ONE);
System.out.println(MyType.TWO);
}
}

this is one
this is two
Another interesting fact is, once you override toString() method, you in effect turn each element into an anonymous inner class. So after compiling the above enum class, you will see a long list of class files:
MyType.class
MyType$1.class
MyType$2.class

10/25/2006

Java Enum and Its Superclass

All java enum E implicitly extends java.lang.Enum<E>. Since java doesn't allow multiple inheritance, enum types can't have superclass. They can't even extend from java.lang.Enum, nor java.lang.Object. It also means enum A can't inherit or extend enum B.

For example, the following is an invalid enum declaration:

public enum MyType extends Object {
ONE, TWO
}
Compiler error:
MyType.java:3: '{' expected
public enum MyType extends Object {
MyType.java:6: identifier expected
2 errors
The correct form should be:
public enum MyType {
ONE, TWO
}
More posts about java enum:
Tags: ,

10/11/2006

Use library-directory in JavaEE 5 apps

Starting from JavaEE 5, you can specify a directory inside the an EAR file to hold jar files that can be used by all modules of that EAR. For example, if you've built an EAR called hello.ear:

hello.ear:
META-INF/application.xml
shared/util-1.jar
shared/util-2.jar
hello-ejb.jar
hello.war
The content of META-INF/application.xml:
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/application_5.xsd">

<module>
<ejb>hello-ejb.jar</ejb>
</module>

<module>
<web>
<web-uri>hello.war</web-uri>
<context-root>hello</context-root>
</web>
</module>

<library-directory>shared</library-directory>
</application>
All classes and resources in all jar files under shared directory (e.g., util-1.jar, util-2.jar) are accessible to hello-ejb.jar and hello.war. For instance, you may choose to put hello-ejb's business interfaces, component interfaces and home interfaces in util-1.jar, to avoid duplicates in ejb jar and war.

Better yet, you don't even need to have an application.xml to use this mechanism. Recall that all descriptors are optional in JavaEE 5. The default library-directory is a directory named lib inside the EAR. You just put your shared jar files here and they will be automatically made accessible for all components. However, these files do need to use *.jar extension.