Wednesday, January 31, 2007

Java Serialization Review

Java Serialization is always a tricky place and a hot spot for java job interview. Two important things:
1. If the Super class is not serializable and the sub class is. Then one important requirement is that the Superclass must have a non-arg constructor accessible by the sub class. Otherwise run time exception. Also all the fields in the super class will not be restored through serialization. ( The Default value or values set in the super class constructor will be used for these fields)

2. If the serializable contains a member variable which is not Serializable. Runtime exception will throw. The easy workaround is to mark the non-serializable object as a static memeber. Static member will not be serialized and default value is used. This also reflect why we should use POJO as much as possible and avoid complex non-serializable objects. Normally these objects are Unit object and should not be included in a transfer object at all.

Websphere session bean remote invokation tips

Here is how to access remote session bean in Websphere 6.0 server.


For remote session bean lookup, use the following code:


public class RemoteTest {
public static void main(String[] args) {
try {
Properties prop = new Properties();
prop.put(Context.INITIAL_CONTEXT_FACTORY, "com.ibm.websphere.naming.WsnInitialContextFactory");
prop.put(Context.PROVIDER_URL, "corbaloc:iiop:localhost:2809");
Context initContext = new InitialContext(prop);
EchoHome echoHome = (EchoHome) PortableRemoteObject.narrow(
initContext.lookup("ejb/com/yuan/EchoHome"), EchoHome.class);
Echo echo = (Echo) PortableRemoteObject.narrow(
echoHome.create(), Echo.class);
System.out.println("AAA" + echo.print());

} catch (Exception e) {
e.printStackTrace();
}
}
}


Two Technical points:

1. All client side library must be in the classpath to avoid exception.
The easy way is to include all jars under the server/lib dir.

2. The lookup address should be the raw name of the session bean (including full class name).
It is different from the lookup in the container environment (java:comp/env/ejb/Echo).