Domanda

I have implemented a few Java classes which extend the abstract java.lang.Number class. I have no immediate need for serializing objects of these classes. However, I do want to provide the rest of the Number contract for these classes which represent "numbers." The trouble is that java.lang.Number implements Serializable. As such, my classes are supposed to provide public default (i.e. no-args) constructors -- my IDE complains, but the compiler will still compile my classes. Fine, but providing public default constructors for "immutable" objects requires providing a default value when the constructor is invoked for any reason other than serialization -- ignore for the moment that these classes return objects from static factory methods and expose no public constructors now. Well, zero is a fine default in many cases, but natural numbers -- i.e. positive integers -- do not include zero in their domain and no single number is any more "special" than any other...O.K...."one" is always "special"...

Etc., etc., etc....

I did look into how BigDecimal handles Number and Serializable in an effort to determine the "right" way to address this question. However, both the JavaDoc and the source code I have been able to examine reveals BigDecimal does not provide a "no-args" constructor despite having extended Number. Realizing that:

Just because Sun Microsystems/Oracle implemented it that way doesn't make it "right."

I am back to the basic question:

What is the "right" way to extend java.lang.Number? If providing a "no-args" constructor is just another Java convention following the rule:

It's not a law, just a good idea...

Is the best answer to avoid the warts by ignoring the "convention?" If so, how can I satisfy an IDE -- Intellij, in particular -- and any Java-to-other-language-or-environment translator which might choose to be more strict than the Java compiler when Serializable raises its ugly head?

È stato utile?

Soluzione 3

You can also make the empty constructor protected, this way serialization still works. What Sun did for BigDecimal was providing readObject and writeObject methods , see here for further details.

Altri suggerimenti

Well, there's always good ol 'NaN' -- Not a number. If you can represent it, that is.

My opinion is that one could forget about being compatible with Java's built-in serialization after looking at the benchmarks. It's 8x slower than textual Jackson and seems being just outdated.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top