Please consider the following example:
public final class ImmutableWrapper<T extends Number> {
private final T value;
public ImmutableWrapper(T value) {
// a subclass of Number may be mutable
// so, how to defensively copying the value?
this.value = value;
}
public T getValue() {
// the same here: how to return a copy?
return value;
}
}
In order to make this class immutable, I must defensively copy any mutable parameter passed to the constructor and create copies of internal mutable objects returned by public methods.
Is this possible? If not, is there any workaround?
Since all Numbers are Serializable you can create copies by serializing/deserializing them.
Maybe you can use apache commons-lang's SerializationUtils.clone(Serializable).
public final class ImmutableWrapper<T extends Number> {
private final T value;
public ImmutableWrapper(T value) {
// a subclass of Number may be mutable
// so, how to defensively copying the value?
this.value = SerializationUtils.clone(value);
}
public T getValue() {
// the same here: how to return a copy?
return SerializationUtils.clone(value);
}
}
or if you want to implement it by yourself take a look at:
Cloning of Serializable and Non-Serializable Java Objects
You need to clone the object. So your code would look like:
public final class ImmutableWrapper<T extends Number> {
private final T value;
public ImmutableWrapper(T value) {
this.value = value.clone();
}
public T getValue() {
return value.clone();
}
}
Related
So I have a generic class which I want to have the method copy():
public class MyGenericClass<T> {
public MyGenericClass( T value ) {
this.value = value;
}
public T value;
public MyGenericClass<T> copy() {
/* Some way to deep copy 'this' */
}
}
One way I know to do this uses lambda expressions:
import java.util.function.UnaryOperator;
public class MyGenericClass<T> {
public MyGenericClass( T value, UnaryOperator<T> copyLambda ) {
this.value = value;
this.copyLambda = copyLambda;
}
public T value;
private final UnaryOperator<T> copyLambda;
public MyGenericClass<T> copy() {
return new MyGenericClass<>( copyLambda.apply( value ), copyLambda )
}
}
However this can quickly end up with a huge amount of constructor arguments which would be hard for an individual to manage.
Another way is to require the generic type to implement an interface:
public interface Copyable<T implements Copyable<T>> {
T copy();
}
public class MyGenericClass<T implements Copyable<T>> implements Copyable<MyGenericClass<T>> {
public MyGenericClass( T value ) {
this.value = value;
}
public T value;
#Override
public MyGenericClass<T> copy() {
return new MyGenericClass<>( value.copy )
}
}
(java.util.function.Supplier can be used in exactly the same way only the method would be called get() not copy())
But this is also annoying for the end user as all generics they wish to use have to implement this unnecessary interface.
And apparently there is some way to deep copy using serialize and deserialize which sounds rather hacky.
Which one of these approaches should I use?
Do I use lambda expressions for copying things and create a factory class to deal with the long constructors?
Or do I require all generics that end up as field types to implement an interface?
I have a generic interface like this:
interface A<T> {
T getValue();
}
This interface has limited instances, hence it would be best to implement them as enum values. The problem is those instances have different type of values, so I tried the following approach but it does not compile:
public enum B implements A {
A1<String> {
#Override
public String getValue() {
return "value";
}
},
A2<Integer> {
#Override
public Integer getValue() {
return 0;
}
};
}
Any idea about this?
You can't. Java doesn't allow generic types on enum constants. They are allowed on enum types, though:
public enum B implements A<String> {
A1, A2;
}
What you could do in this case is either have an enum type for each generic type, or 'fake' having an enum by just making it a class:
public class B<T> implements A<T> {
public static final B<String> A1 = new B<String>();
public static final B<Integer> A2 = new B<Integer>();
private B() {};
}
Unfortunately, they both have drawbacks.
As Java developers designing certain APIs, we come across this issue frequently. I was reconfirming my own doubts when I came across this post, but I have a verbose workaround to it:
// class name is awful for this example, but it will make more sense if you
// read further
public interface MetaDataKey<T extends Serializable> extends Serializable
{
T getValue();
}
public final class TypeSafeKeys
{
static enum StringKeys implements MetaDataKey<String>
{
A1("key1");
private final String value;
StringKeys(String value) { this.value = value; }
#Override
public String getValue() { return value; }
}
static enum IntegerKeys implements MetaDataKey<Integer>
{
A2(0);
private final Integer value;
IntegerKeys (Integer value) { this.value = value; }
#Override
public Integer getValue() { return value; }
}
public static final MetaDataKey<String> A1 = StringKeys.A1;
public static final MetaDataKey<Integer> A2 = IntegerKeys.A2;
}
At that point, you gain the benefit of being a truly constant enumeration value (and all of the perks that go with that), as well being an unique implementation of the interface, but you have the global accessibility desired by the enum.
Clearly, this adds verbosity, which creates the potential for copy/paste mistakes. You could make the enums public and simply add an extra layer to their access.
Designs that tend to use these features tend to suffer from brittle equals implementations because they are usually coupled with some other unique value, such as a name, which can be unwittingly duplicated across the codebase for a similar, yet different purpose. By using enums across the board, equality is a freebie that is immune to such brittle behavior.
The major drawback to such as system, beyond verbosity, is the idea of converting back and forth between the globally unique keys (e.g., marshaling to and from JSON). If they're just keys, then they can be safely reinstantiated (duplicated) at the cost of wasting memory, but using what was previously a weakness--equals--as an advantage.
There is a workaround to this that provides global implementation uniqueness by cluttering it with an anonymous type per global instance:
public abstract class BasicMetaDataKey<T extends Serializable>
implements MetaDataKey<T>
{
private final T value;
public BasicMetaDataKey(T value)
{
this.value = value;
}
#Override
public T getValue()
{
return value;
}
// #Override equals
// #Override hashCode
}
public final class TypeSafeKeys
{
public static final MetaDataKey<String> A1 =
new BasicMetaDataKey<String>("value") {};
public static final MetaDataKey<Integer> A2 =
new BasicMetaDataKey<Integer>(0) {};
}
Note that each instance uses an anonymous implementation, but nothing else is needed to implement it, so the {} are empty. This is both confusing and annoying, but it works if instance references are preferable and clutter is kept to a minimum, although it may be a bit cryptic to less experienced Java developers, thereby making it harder to maintain.
Finally, the only way to provide global uniqueness and reassignment is to be a little more creative with what is happening. The most common use for globally shared interfaces that I have seen are for MetaData buckets that tend to mix a lot of different values, with different types (the T, on a per key basis):
public interface MetaDataKey<T extends Serializable> extends Serializable
{
Class<T> getType();
String getName();
}
public final class TypeSafeKeys
{
public static enum StringKeys implements MetaDataKey<String>
{
A1;
#Override
public Class<String> getType() { return String.class; }
#Override
public String getName()
{
return getDeclaringClass().getName() + "." + name();
}
}
public static enum IntegerKeys implements MetaDataKey<Integer>
{
A2;
#Override
public Class<Integer> getType() { return Integer.class; }
#Override
public String getName()
{
return getDeclaringClass().getName() + "." + name();
}
}
public static final MetaDataKey<String> A1 = StringKeys.A1;
public static final MetaDataKey<Integer> A2 = IntegerKeys.A2;
}
This provides the same flexibility as the first option, and it provides a mechanism for obtaining a reference via reflection, if it becomes necessary later, therefore avoiding the need for instantiable later. It also avoids a lot of the error prone copy/paste mistakes that the first option provides because it won't compile if the first method is wrong, and the second method does not need to change. The only note is that you should ensure that the enums meant to be used in that fashion are public to avoid anyone getting access errors because they do not have access to the inner enum; if you did not want to have those MetaDataKeys going across a marshaled wire, then keeping them hidden from outside packages could be used to automatically discard them (during marshaling, reflectively check to see if the enum is accessible, and if it is not, then ignore the key/value). There is nothing gained or lost by making it public except providing two ways to access the instance, if the more obvious static references are maintained (as the enum instances are just that anyway).
I just wish that they made it so that enums could extend objects in Java. Maybe in Java 9?
The final option does not really solve your need, as you were asking for values, but I suspect that this gets toward the actual goal.
If JEP 301: Enhanced Enums gets accepted, then you will be able to use syntax like this (taken from proposal):
enum Primitive<X> {
INT<Integer>(Integer.class, 0) {
int mod(int x, int y) { return x % y; }
int add(int x, int y) { return x + y; }
},
FLOAT<Float>(Float.class, 0f) {
long add(long x, long y) { return x + y; }
}, ... ;
final Class<X> boxClass;
final X defaultValue;
Primitive(Class<X> boxClass, X defaultValue) {
this.boxClass = boxClass;
this.defaultValue = defaultValue;
}
}
By using this Java annotation processor https://github.com/cmoine/generic-enums, you can write this:
import org.cmoine.genericEnums.GenericEnum;
import org.cmoine.genericEnums.GenericEnumParam;
#GenericEnum
public enum B implements A<#GenericEnumParam Object> {
A1(String.class, "value"), A2(int.class, 0);
#GenericEnumParam
private final Object value;
B(Class<?> clazz, #GenericEnumParam Object value) {
this.value = value;
}
#GenericEnumParam
#Override
public Object getValue() {
return value;
}
}
The annotation processor will generate an enum BExt with hopefully all what you need!
if you prefer you can also use this syntax:
import org.cmoine.genericEnums.GenericEnum;
import org.cmoine.genericEnums.GenericEnumParam;
#GenericEnum
public enum B implements A<#GenericEnumParam Object> {
A1(String.class) {
#Override
public #GenericEnumParam Object getValue() {
return "value";
}
}, A2(int.class) {
#Override
public #GenericEnumParam Object getValue() {
return 0;
}
};
B(Class<?> clazz) {
}
#Override
public abstract #GenericEnumParam Object getValue();
}
The problem I'm having has already been asked before: How to implement an interface with an enum, where the interface extends Comparable?
However, none of the solutions solve my exact problem, which is this:
I have a value object, similar to BigDecimal. Sometimes this value will not be set with a real object, because that value is not yet known. So I want to use the Null Object Pattern to represent the times this object is not defined. This is all not a problem, until I try to make my Null Object implement the Comparable interface. Here's an SSCCE to illustrate:
public class ComparableEnumHarness {
public static interface Foo extends Comparable<Foo> {
int getValue();
}
public static class VerySimpleFoo implements Foo {
private final int value;
public VerySimpleFoo(int value) {
this.value = value;
}
#Override
public int compareTo(Foo f) {
return Integer.valueOf(value).compareTo(f.getValue());
}
#Override
public int getValue() {
return value;
}
}
// Error is in the following line:
// The interface Comparable cannot be implemented more than once with different arguments:
// Comparable<ComparableEnumHarness.NullFoo> and Comparable<ComparableEnumHarness.Foo>
public static enum NullFoo implements Foo {
INSTANCE;
#Override
public int compareTo(Foo f) {
return f == this ? 0 : -1; // NullFoo is less than everything except itself
}
#Override
public int getValue() {
return Integer.MIN_VALUE;
}
}
}
Other concerns:
In the real example, there are multiple subclasses of what I'm calling Foo here.
I could probably work around this by having NullFoo not be an enum, but then I can't guarantee there is ever only exactly one instance of it, i.e. Effective Java Item 3, pg. 17-18
I don't recommend the NullObject pattern because I always find myself in one of these 2 situations:
it does not make sense to use NullObject like an object, and it should stay null
NullObject has too much meaning to be just a NullObject, and should be a true object itself (for instance, when it acts like a fully functional default value)
According to our discussion in the comments, it seems to me that your NullObject behaves very much like the 0 value of your normal objects.
What I would do is actually use 0 (or whatever default value makes more sense), and put a flag if you really need to know whether it has been initialized. This way, you will have 2 things to consider:
all uninitialized values won't share the same instance with my solution
for the very same reason, you are now able to initialize your object later without having to create a new instance
Here is the kind of code I think of:
public static class VerySimpleFoo implements Foo {
private int value;
private boolean initialized;
public VerySimpleFoo() {
this.value = 0; // whatever default value makes more sense
this.initialized = false;
}
public VerySimpleFoo(int value) {
this.value = value;
this.initialized = true;
}
#Override
public int compareTo(Foo f) {
// possibly need some distinction here, depending on your default value
// and the behavior you expect
return Integer.valueOf(value).compareTo(f.getValue());
}
#Override
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
this.initialized = true;
}
public boolean isInitialized() {
return initialized;
}
}
As you suggested, I believe one solution would be to use a class instead of an enum:
public class NullFoo implements Foo {
private NullFoo() {
}
public static final Foo INSTANCE = new NullFoo();
#Override
public int compareTo(Foo f) {
return f == this ? 0 : -1;
}
#Override
public int getValue() {
return 0;
}
}
This mimics an enum behavior, but it allows you to implement your Foo interface. The class is not instantiable because of the private constructor, so the only instance available is the one accessible via NullFoo.INSTANCE, which is thread-safe (thanks to the final modifier).
The thing is that Enum already implements Comparable natively, and since the generics are just a sugar code, and lost after compilation, effectively you want to implement the same method twice for the same interface.
I would drop enum, for NullFoo, converting it to class (like you suggested), and make final public static INSTANCE reference with private constructor, (This is not as good as using an enum, but acceptable, in most cases).
I have a class that should accept different datatypes as the second constructor parameter:
public abstract class QueryMatch {
String key;
Object input;
public <T> QueryMatch(String key, T o) {
this.key = key;
input = o;
}
public String getKey() {
return key;
}
public Object getValue() {
return input;
}
}
I don't want to use type parameters, like
public abstract class QueryMatch<T>{
String key;
T input;
...
As this way I'm getting raw types warnings when declaring retrieving QueryMatch as a generic (as I don't know the datatype it contains). But the problem is that I need to return the value and I'm not totally comfortable by returning an Object (is that just me, but it doesn't seem like a good practice?).
Additionally, another class inherits from it:
public class QueryMatchOr extends QueryMatch {
public QueryMatchOr() {
super("title", new ArrayList<String>());
}
public void addMatch(String match) {
((ArrayList<String>) input).add(match);
}
}
And of course I'm getting a Unchecked cast warning (which I can avoid with #SuppressWarnings(“unchecked”)).
So, my question is... is there a better way to achieve what I'm trying to do? An abstract class that contains an object (which could be bounded), and returning the datatype it contains (instead of an Object) without using a type parameter in the class declaration?
What you are doing is not a good design. You are using an Object type field from the superclass while you only can know it's actual (needed) type in the subclass. If you only know that in the subclass, declare that variable in the subclass. Not even to mention that your fields are not private.
How about:
public abstract class QueryMatch {
private String key;
public QueryMatch(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public abstract void addMatch(String match);
}
public class QueryMatchOr extends QueryMatch {
private ArrayList<String> input;
public QueryMatchOr() {
super("title");
input = new ArrayList<String>();
}
public void addMatch(String match) {
input.add(match);
}
}
If you need the getValue() method in the superclass, you really should make it generic:
public abstract class QueryMatch<T> {
private String key;
public QueryMatch(String key) {
this.key = key;
}
public String getKey() {
return key;
}
public abstract void addMatch(String match);
public abstract T getValue();
}
public class QueryMatchOr extends QueryMatch<ArrayList<String>> {
private ArrayList<String> input;
public QueryMatchOr() {
super("title");
input = new ArrayList<String>();
}
public void addMatch(String match) {
input.add(match);
}
public ArrayList<String> getValue(String match) {
input;
}
}
So first, I think the best answer is to make your class generic. But if you really don't want to do this you could do something like this:
public <T> T getValue(Class<T> type) {
return (T)input;
}
In some way you need to provide the expected type for the return value to the class. This can either be done my making that class generic or the method generic.
So, my question is... is there a better way to achieve what I'm trying to do?
No, there isn't.
I think you should use generics instead of #SuppressWarnings(“unchecked”))
I've made an example to demonstrate my problem:
Metrical.java
public interface Metrical<T>
{
double distance(T other);
}
Widget.java
public class Widget implements Metrical<Widget>
{
private final double value;
public Widget(double value) { this.value = value; }
public double getValue() { return value; }
public double distance(Widget other) { return Math.abs(getValue() - other.getValue()); }
}
Pair.java
public class Pair<T>
{
private final double value;
private final T object1, object2;
public Pair(T object1, T object2, double value)
{
this.object1 = object1;
this.object2 = object2;
this.value = value;
}
public T getObject1() { return object1; }
public T getObject2() { return object2; }
public double getValue() { return value; }
}
Algorithm.java
import java.util.Set;
public class Algorithm<T extends Metrical<T>>
{
public void compute(Set<T> objects)
{
}
public void compute(Set<Pair<T>> pairs)
{
}
}
So, in Algorithm.java, Set< Pair< T >> is being seen as a Set< T > and thus I am having type erasure problems. However, is there any way I can get away with something like this without naming the methods differently? Both variants of the algorithm are meant to operate on T's, but I need to allow for different arguments. They compute the same thing, so in an effort to avoid confusion, I would rather not name them differently. Is there any way to accommodate this?
No there isn't.
You have to remember that someone could call your method with just a vanilla Set, in which case which one would be called?
That's why you can't do it. Just like you can't do:
interface A {
void blah(Set set);
void blah(Set<T> set);
}
Same problem.
The type information isn't available at runtime (ie type erasure).
Sorry, the bad news is that you cannot do this:
public class Algorithm<T extends Metrical<T>> {
public void compute(Set<T> objects) {
}
public void compute(Set<Pair<T>> pairs) {
}
}
Due to erasure, both will erase to the same signature. There is no way around this short of renaming one of the methods.
Sadly, this is the major area where Java Generics falls down... there is just no good solution.
I've generally resorted to making a new class, with the interface as Set<Pair<T>>, but that wraps Set<Pair<T>> (without extending it, which would cause the same problem).
I've written an article about type erasure which can be of your interest.
It gives the common widely known solution and also a tricky way to circumvent the problem.
I don't know if it will be relevant for you. Anyway, it contains some techniques which may be useful under certain circumstances.
See also: Using TypeTokens to retrieve generic parameters
I hope it helps.
Use public class Widget<K, P> implements Metrical<K extends Widget<P>>.
public double distance(Widget other) {} becomes public double distance(Widget<P> other) {}