Reputation: 2761
I have a class with a couple of methods that convert from one generic type to another, but I want to return the original value if both: the argument type and the return type are the same. The best option I could come up with was to cast the argument type and wrap it in a try catch statement, but that seems dirty to me.
public WK wrapKey(K key) {...
public abstract class MyClass<K, V extends Comparable, WK, WV> extends BaseClass<Map<WK, WV>, KeyValueBean<K, V>> {
...
public WK wrapKey(K key) {
try {
return (WK) key;
} catch (Exception e) {
return null;
}
}
public WV wrapValue(V value) {
try {
return (WV) value;
} catch (Exception e) {
return null;
}
}
I thought the other option could be to specify the class type as an argument in the constructor or a setter method, and then use isAssignableFrom:
public WV wrapValue(V value) {
if (value.class.isAssignableFrom(this.getWrappedValueClass())){
return WK(V);
}
return null;
}
Is there any other way??
Upvotes: 1
Views: 125
Reputation: 70731
Java implements generics through type erasure, which means all type checks are performed at compile-time and then the generics are erased at runtime. Because of this, your code below actually does nothing at all:
public WV wrapValue(V value) {
try {
return (WV) value;
} catch (Exception e) {
return null;
}
}
At runtime, this is equivalent to:
public Object wrapValue(Object value) {
return value;
}
This method will never throw an exception, instead the caller of this method might, because the compiler adds an implicit cast at the call site.
Your second example won't even compile because you cannot do value.class
. You would have to pass in the class types for both V
and KV
if you want to do this check.
In any case, your design seems overly complicated -- perhaps if you explain what you are trying to do, there might be a better solution.
Upvotes: 2