I have a base custom exception class BaseException
public class BaseException extends RuntimeException {
}
and several custom exceptions that extends BaseException
public class CustomException extends BaseException {
private static final long serialVersionUID = 3655655808021733968L;
}
I got a warning about serial version uid being not declared in the BaseException class. Is it needed in an abstract class? Is it a good practice? Is any way to get rid of the warning?
Yes, you need to define the serialVersionUID in an abstract class. Serialization serializes instance state, which usually means the non-static fields; any inherited state needs to be serialized along with the rest of the object’s state.
The fact that you don’t have fields in BaseException doesn’t mean you should skip the serialVersionUID.
Note that, contrary to popular belief, a serialVersionUID does not need to be based on a hash of the class’s name or structure. Only the default computed serial version UID does this, when the class does not define a serialVersionUID field explicitly. Normally, you can declare it as a simple number:
private static final long serialVersionUID = 1;
Related
At somewhere, that I can not remember, I read about an alternative way to instatiate a object:
Generally, we instantiate (and assign) this way:
User userObj = new User();
userObj.setId(1);
userObj.setName("Foo");
An alternative way could be:
User userObj = new User()
{{
setId(1);
setName("Foo");
}}
I was using this alternative, and it works.
1) Anyone knows what is it? Where is Java documentation link that metion about it?
I stop to use this because I was having problems with interfaces that ClassName implements, but the alternative way don't implements. Oo
public class User implements Serializable
{
private int id;
private String name;
//public Getters and Setters
}
2) When I try to serialize and use it (passing from one activity to another, using:
putExtra(String, Serializable)
it will throw NotSerializableException. Why?
Edit 1: An anonnymous class also implements the parent 'implementations', like Serializable from ClassName?
You are using anonymous class with initialization block. So it's just an equivalent to the:
SubClass extends ClassName{
{
classObj.setParam1(1);
classObj.setParam2(1);
}
}
new SubClass();
There is nothing wrong with this construction - but please notice that you are not creating object of ClassName class, but object of SubClass class.
As I said you are using anonymous class (class without name). This is bad - cause while serialization / deserialization JVM should exactly know what is the class of serialization data, so basically - don't use anonymous classes if you want to serialize them.
Ad 1.: This construct ist called "anonymous class".
Ad 2.: I bet your class contains a field which is not Serializable.
I'm getting a serialization compatibility error from the below two classes. Only the parent class, CommericalCustomer implements serialization. What is the proper way to use the Serializable Interface when having a parent/child relation as I have below?
public class CachedCommercialCustomers extends CommercialCustomer {
}
public class CommercialCustomer implements Serializable {
private static final long serialVersionUID = 1L;
}
Exception:
[#|2013-01-02T05:01:02.553-0800|SEVERE|glassfish3.1.2|com.hazelcast.nio.AbstractSerializer|_ThreadID=10;_ThreadName=Thread-2;|spot.api.model.vo.backoffice.CachedCommercialCustomers; local class incompatible: stream classdesc serialVersionUID = -2672531984245897526, local class serialVersionUID = -743225273062282831
java.io.InvalidClassException: com.sample.CachedCommercialCustomers; local class incompatible: stream classdesc serialVersionUID = -2672531984245897526, local class serialVersionUID = -743225273062282831
at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:579)
at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1600)
at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1513)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1749)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1346)
at java.io.ObjectInputStream.readUnshared(ObjectInputStream.java:458)
at com.hazelcast.nio.DefaultSerializer$ObjectSerializer.readNormal(DefaultSerializer.java:383)
at com.hazelcast.nio.DefaultSerializer$ObjectSerializer.read(DefaultSerializer.java:353)
at com.hazelcast.nio.DefaultSerializer.read(DefaultSerializer.java:134)
at com.hazelcast.nio.CustomSerializerAdapter.read(CustomSerializerAdapter.java:33)
at com.hazelcast.nio.AbstractSerializer.toObject(AbstractSerializer.java:116)
at com.hazelcast.nio.AbstractSerializer.toObject(AbstractSerializer.java:146)
at com.hazelcast.nio.Serializer.readObject(Serializer.java:72)
at com.hazelcast.impl.ThreadContext.toObject(ThreadContext.java:103)
at com.hazelcast.nio.IOUtil.toObject(IOUtil.java:149)
at com.hazelcast.impl.BaseManager$RequestBasedCall.getResultAsObject(BaseManager.java:384)
at com.hazelcast.impl.BaseManager$ResponseQueueCall.getResultAsObject(BaseManager.java:455)
at com.hazelcast.impl.BaseManager$RequestBasedCall.getResultAsObject(BaseManager.java:368)
at com.hazelcast.impl.BaseManager$ResponseQueueCall.getResultAsObject(BaseManager.java:455)
The problem here is that you don't specify a serialVersionId for your sub class - so java will generate one for you instead. A simple recompilation might change this value if you change the java source file. See the spec.
The fact that the I'd changes when the code changes is a good thing, but in some cases it will cause you some grief :)
See here for more information and how to "fix" the problem if necessary.
I have some Serializable Objects which I use with GWT's RPC mechanism.
I decided to make them all sub-class an Object containing common fields such as "id", "revision" etc.
However, I've noticed that GWT does not serialize fields of the super-class, so I just get every super-class field as null on the client-side.
How can I get the super-class fields serialized as well without having to write a CustomFieldSerializer for each and every one of my Serializable classes? Is it possible?
Example:
public class Super {
private String id;
public String getId() {
return id;
}
}
public class Sub extends Super implements Serializable {
private String name;
// more stuff here
}
// on the client side, inside an AsyncCallback
onSuccess(Sub sub) {
assert(sub.getId() != null);
}
So, when I send this through GWT's RPC mechanism to the client-side, I get a null value in the 'id' field of any instance of Sub. I ensured that in the server, id is not null. I also tried to make the super-class implement Serializable, without luck.
Any advices welcome.
For serialize any class in gwt you have to implements Serializable in super class.
To pass a bean you have to fulfill the following requirements (from GWT site):
1.It implements either Java Serializable or GWT IsSerializable interface, either directly, or because it derives from a superclass that does.
2.Its non-final, non-transient instance fields are themselves serializable
3.It has a default (zero argument) constructor with any access modifier (e.g. private Foo(){} will work)
The problem may have different causes.
1.Verify that the class has a default constructor (without arguments)
2.Verify that the class implements Serializable or IsSerializable or implements an Interface that extends Serializable or extends a class that implement Serializable
3.Verify that the class is in a client.* package or …
4.Verify, if the class is not in client.* package, that is compiled in your GWT xml module definition. By default is present. If your class is in another package you have to add it to source. For example if your class is under domain.* you should add it to xml as . Be aware that the class cannot belong to server package!
5.If you are including the class from another GWT project you have to add the inherits to your xml module definition. For example if your class Foo is in the package com.dummy.domain you have to add to the module definition.
6.If you are including the class from another GWT project released as a jar verify that the jar contains also the source code because GWT recompile also the Java source for the classes passed to the Client.
If you want the data in Super to be serialized, you must make it Serializable.
Are private interfaces ever used in design decisions ? If so, what are the reasons and when do you know the need for a private interface?
A top-level interface cannot be private. It can only have public or package access. From the Java Language Specification, section 9.1.1: "Interface Modifiers":
The access modifiers protected and private pertain only to member interfaces whose declarations are directly enclosed by a class declaration (§8.5.1).
A nested interface can be private whenever it and its subclasses, if any, are an implementation detail of its top-level class.
For example, the nested interface CLibrary below is used as an implementation detail of the top-level class. It's used purely to define an API for JNA, communicated by the interface's Class.
public class ProcessController {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary( "c", CLibrary.class );
int getpid();
}
public static int getPid() {
return CLibrary.INSTANCE.getpid();
}
}
As another example, this private interface defines an API used by private nested classes implementing custom formatting symbols.
public class FooFormatter {
private interface IFormatPart {
/** Formats a part of Foo, or text.
* #param foo Non-null foo object, which may be used as input.
*/
void write( Foo foo ) throws IOException;
}
private class FormatSymbol implements IFormatPart { ... }
private class FormatText implements IFormatPart { ... }
...
}
IMHO You cannot usefully make an interface private.
However I often have two interfaces, one for public use and one for internal use. The internal use interface I make package local if possible e.g.
public interface MyInterface {
public void publicMethod();
}
interface DirectMyInterface extends MyInterface {
public void internalUseOnlyMethod();
}
The internal use methods expose methods I don't want other developers to use and/or I want to be able to change easily. The reason I have the interface at all is that I have several implementations which I want to use internally via an interface.
It has to be package protected if the interface if for internal use.
In general if the interface hasn't any interest outside it's ambit it's a good api design decision to hide it because there's less complexity for the users of the interface and also allows you to refactor it more easily, because when the interface is public and in the API you loss the liberty to change it.
A private interface method is a method that is only accessible within the class or object in which it is defined.
This allows for better organization and maintainability of code, as well as increased security by preventing external access to sensitive data or functionality.
According to the App Engine docs, the PersistenceManagerFactory should only be created once in the application.
It provides this sample:
package guestbook;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance =
JDOHelper.getPersistenceManagerFactory("transactions-optional");
private PMF() {}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
Why does PMF.java have to be a "public final class" in addition to making the pmfInstance a "private static final" object?
Classes should be final unless there's a good reason for them not to be.
There is no use case in which one would want to inherit from the PMF, so it should be final.
PMF is a class that should not be instantiated, since it has no instance state or methods, it is strictly there to provide static methods and global state.
Item 4 in Effective Java provides this idiom, however it does not add that the class should be made final, as it would be impossible to subclass it anyway with a private constructor. And there it is explicitly recommended that the private constructor be documented to avoid exactly the confusion you are having.
In addition, this code sample is providing the Static Initialization workaround for double check locking.