Dynamic casting in Java - java

Before I get chided for not doing my homework, I've been unable to find any clues on the multitude of questions on Java generics and dynamic casting.
The type Scalar is defined as follows:
public class Scalar <T extends Number> {
public final String name;
T value;
...
public T getValue() {
return value;
}
public void setValue(T val) {
this.value = val;
}
}
I would like to have a method that looks like this:
public void evilSetter(V val) {
this.value = (T) val;
}
Sure, this is generally discouraged. The reason I want such a method is because I have a collection of Scalars whose values I'd like to change later. However, once they go in the collection, their generic type parameters are no longer accessible. So even if I want make an assignment that's perfectly valid at runtime, there's no way of knowing that it'll be valid at compile time, with or without generics.
Map<String, Scalar<? extends Number>> scalars = ...;
Scalar<? extends Number> scalar = scalars.get("someId");
// None of this can work
scalar.value = ...
scalar.setValue(...)
So how do I implement a checked cast and set method?
public <V extends Number> void castAndSet(V val) {
// One possibility
if (this.value.getClass().isAssignableFrom(val.getClass()) {
// Some cast code here
}
// Another
if (this.value.getClass().isInstanceOf(val) {
// Some cast code here
}
// What should the cast line be?
// It can't be:
this.value = this.value.getClass().cast(val);
// Because this.value.getClass() is of type Class<?>, not Class<T>
}
So I'm left with using
this.value = (T) val;
and catching a ClassCastException?

You have:
this.value.getClass().isAssignableFrom(val.getClass())
This is probably going to be a problem unless you can be certain value will never be null.
You also have:
this.value = (T) val;
This will only cast to Number and not to T because under the hood T is just a Number due to type-erasure. Therefore if value is a Double and val is an Integer, no exception will be thrown.
If you actually want to perform a checked cast, you must have the correct Class<T> object. This means you should be passing Class<T> in the constructor of your object. (Unless you can be sure value is never null, in which case you can go with your first idea.) Once you have that object (stored in a field), you can perform the checked cast:
T value = valueClass.cast(val);

Related

Parameterize a class with one of a fixed set of types

Say I have a generic class Foo which can hold an object of type T. Furthermore, let's say I only want to be able to instantiate the class with objects that are one of two types. Finally, let's say that the lowest common upper bound of these two types is a type that has many more subclasses than those two types that I want to allow, so I can't simply specify an upper bound for the type parameter (as in class Foo<T extends Something>), because then I would allow to instantiate the class with other types than the two I expect.
For illustration, let's say I want Foo to hold only either a String or an Integer. The lowest common upper bound is Object, so specifying an upper bound won't do the trick.
Certainly, I could do something along the lines of
class Foo<T> {
private T obj;
public Foo(T obj) throws IllegalArgumentException {
if (!(obj instanceof String || obj instanceof Integer)) {
throw new IllegalArgumentException("...");
}
this.obj = obj;
}
}
However, in this case, I can still call the constructor with any object; if I try to instantiate it with something that is neither a String nor an Integer, I will get an exception at runtime.
I would like to do better. I would like the compiler to infer statically (i.e., at compile time) that I can only instantiate this class with objects that are either String or Integer.
I was thinking something along those lines might do the trick:
class Foo<T> {
private T obj;
public Foo(String s) {
this((T) s);
}
public Foo(Integer i) {
this((T) i);
}
private Foo(T obj) {
this.obj = obj;
}
}
This works, but it looks really, really odd. The compiler warns (understandably) about unchecked casts. Of course I could suppress those warnings, but I feel this is not the way to go. In addition, it looks like the compiler can't actually infer the type T. I was surprised to find that, with the latter definition of class Foo, I could do this, for instance:
Foo<Character> foo = new Foo<>("hello");
Of course, the type parameter should be String here, not Character. But the compiler lets me get away with the above assignment.
Is there a way to achieve what I want, and if yes, how?
Side question: why does the compiler let me get away with the assignment to an object of type Foo<Character> above without even so much as a warning (when using the latter definition of class Foo)? :)
Try using static factory method to prevent compiler warning.
class Foo<T> {
private T obj;
public static Foo<String> of(String s) {
return new Foo<>(s);
}
public static Foo<Integer> of(Integer i) {
return new Foo<>(i);
}
private Foo(T obj) {
this.obj = obj;
}
}
Now you create instance using:
Foo<String> foos = Foo.of("hello");
Foo<Integer> fooi = Foo.of(42);
Foo<Character> fooc = Foo.of('a'); // Compile error
However the following are still valid since you can declare a Foo of any type T, but not instantiate it:
Foo<Character> fooc2;
Foo<Character> fooc3 = null;
Foo<Object> fooob1;
Foo<Object> fooob2 = null;
one word: interface. You want your Z to wrap either A or B. Create an interface implementing the smallest common denominator of A and B. Make your A and B implement that interface. There's no other sound way to do that, AFAIK. What you already did with your constructors etc. is the only other possibility, but it comes with the caveats you already noticed (having to use either unchecked casts, or static factory wrappers or other code smells).
note: If you can't directly modify A and/or B, create wrapper classes WA and WBfor them beforehand.
example:
interface Wrapper {
/* either a marker interface, or a real one - define common methods here */
}
class WInt implements Wrapper {
private int value;
public WInt( int value ) { this.value = value; }
}
class WString implements Wrapper {
private String value;
public WString( String value ) { this.value = value; }
}
class Foo<T> {
private Wrapper w;
public Foo(Wrapper w) { this.w = w; }
}
because you call your private Foo(T obj) due to diamond type inference. As such, it's equal to calling Foo<Character> foo = new Foo<Character>("hello");
Long story short: You are trying to create a union of two classes in java generics which is not possible but there are some workarounds.
See this post
Well the compiler uses the Character class in T parameter. Then the String constructor is used where String is casted to T (Character in this case).
Trying to use the private field obj as a Character will most likely result in an error as the saved value is an instance of the final class String.
Generics is not suitable here.
Generics are used when any class can be used as the type. If you only allow Integer and String, you should not use generics. Create two classes FooInteger and FooString instead.
The implementations should be pretty different anyway. Since Integers and Strings are very different things and you would probably handle them differently. "But I am handling them the same way!" you said. Well then what's wrong with Foo<Double> or Foo<Bar>. If you can handle Integer and String with the same implementation, you probably can handle Bar and Double and anything else the same way as well.
Regarding your second question, the compiler will see that you want to create a Foo<Character>, so it tries to find a suitable overload. And it finds the Foo(T) overload to call, so the statement is perfectly fine as far as the compiler is concerned.

Not implementing generic method in generics class

Imagine code like this:
public class Value<T> {
private T value;
public Value(T value) {
this.value = value;
}
public int size() {
return sizeOf(value);
}
private int sizeOf(int value) {
return Integer.BYTES;
}
private int sizeOf(String value) {
return value.length() * Character.BYTES;
}
}
and somewhere (e.g. main)
Value<String> value = new Value<String>("hello");
The problem is that the code will not compile, because I haven't implemented sizeOf(T value), but I don't understand why would the compiler complain --- it sees that I only use it with <T=String>. And if I implement the generic sizeOf(T value) , it will take precedence (as explained here Java generics (template) specialization possible (overriding template types with specific types) )
Note that the solution proposed there (having a StringValue subclass) doesn't really apply in my case, because I already have some subclasses which I am using, so I would need to create lots of extra classes (times by types)
But I would prefer something much more straight-forward, such as this
You have to declare sizeOf(T value) because T can be of any type, so to maintain type controll, compiler needs "universal" version of sizeOf method that will hindle any possible type.
Think of what would happend if you would use something like new Value<List<Object>>(new ArrayList<Object>).size() - what would happen then as you have no method specialized in returning size of collection?
The thing is, that during runtime, generic type is erased, so JVM have no idea whitch of the overloaded methods should be used. Check more info about type erasure here. https://docs.oracle.com/javase/tutorial/java/generics/erasure.html
There's no getting around having to provide an implementation for size(). Your code is half way to the double dispatch pattern, but going all the way isn't possible, because you've got no way of requiring types like String to implement size().
One approach is to require the size code on construction:
public class Value<T> {
private T value;
private Function<T, Integer> size;
public Value(T value, Function<T, Integer> size) {
this.value = value;
this.size;
}
public int size() {
return size.apply(value);
}
}
To create a Value<String> for example:
Value<String> val = new Value("foo", s -> s.length() * Character.BYTES)
or if that doesn't work, use instanceof for supported types:
public int size() {
if (value instanceof Integer)
return Integer.BYTES;
if (value instanceof String)
return ((String)value).length() * Character.BYTES;
// other supported types
throw new IllegalStateException();
}

How can I construct an EnumSet of generic varargs?

Assume I want to do something like the following:
public static <V> Set<V> setOf(V... elem)
{
Set<V> set = null;
if (elem[0] instanceof Enum)
set = Sets.newEnumSet(elem, elem[0].getClass()); OR
set = EnumSet.<V>noneOf(elem[0].getClass());
return set;
}
Neither of these, or several other variations, seem to work. Can someone explain to me what's going on? I have looked at How do I get the type object of a genericized Enum? and some other similar questions, but I still can't get this to work.
First of all, you need to make sure the type V is restricted to be an enum type; you can do this by specifiying that V must extends Enum<V>.
Then, you will need to provide the Class of the enum type. Due to type-erasure, you won't be able to derive it at run-time. This is needed because, to construct a new empty EnumSet, you need to specify the type of the elements.
Finally, you have several ways to create the set, but the simplest might be to use the Stream API:
#SafeVarargs
public static <V extends Enum<V>> Set<V> setOf(Class<V> enumClass, V... elem) {
return Arrays.stream(elem).collect(Collectors.toCollection(() -> EnumSet.noneOf(enumClass)));
}
Note that if you can guarantee that there will be at least 1 element, you could use EnumSet.copyOf(Arrays.asList(elem)) without the need to pass the class.
If you can't bound the generic parameter to V extends Enum<V>, you can make compilable code as follows:
public <V> Set<V> setOf(V... elem) {
Set<V> set = null;
if (elem[0].getClass().isEnum()) {
set = (Set<V>) EnumSet.copyOf((Collection<Enum>)Arrays.asList(elem)) ;
}
return set;
}
Of course there are unsafe cast warnings.
I also changed the check of the type to:
if (elem[0].getClass().isEnum())
which IMHO is cleaner.

Generic pair with one known class?

I'm implementing a weighted probability algorithm, so I created a generic Pair class. Since the probability is calculated using numbers, the value of Pair would always be an Integer, but I wanted it to work the way where the key could be any Object. This is what I got:
class Pair<K, Integer> {
public K k;
public java.lang.Integer v;
public Pair(K k, java.lang.Integer v) {
this.k = k;
this.v = v;
}
// getters and other stuff
}
It works fine, but I find it weird that no matter what I type instead of the Integer part in the first line, it works the same. Am I missing something? Is there a better way to do that?
class Pair<K, Integer>
is equivalent to
class Pair<K, V>
where the name of the second generic parameter would happen to be Integer instead of V (and thus hiding the type java.lang.Integer, which forces you to use java.lang.Integer instead of just Integer in the code, to avoid a conflict).
Your class should only have one generic parameter:
class Pair<K>
You use generics when you may accept any type.
But since you know that type to be Integer, you do not need to make it generic.
The new version with one generic type argument will look like this:
public class Pair<T> {
public T t;
public int v;
public Pair(T t, int v) {
this.t = t;
this.v = v;
}
// ...
}
It is good practice, when you have just one generic type argument, to name it with the "T" letter.
Also, you can now use int instead of Integer.
The way you use it, Integer is just a type variable, same as K.
If you don't need the type of the second value of the pair to be a parameter, then don't declare it as type parameter, but just use Integer in the code:
class IntPair<K> {
private K first;
private Integer second;
public Integer someIntegerSpecificFunction() {
// do stuff to internalPair.second
}
K getFirst() {
return first;
}
Integer getSecond() {
return second;
}
}

How do I bound a generic type to 2 types that are almost completely separated in hierarchy

How do I do this? Because you can only extend one class so it can only have one upper bound.
In my case I need the generic type to be bounded in String and int. If I use an Integer wrapper instead of int and rely on auto-boxing, I can make it but the problem is other classes can be passed as a type parameter as well.
What's the best way to do this?
You could use the non generic variants of collections (e.g List), or
more cleanly explicitly List<Object> to show code's intention.
Wrap that in a MyList class, and create add(), get() methods for each type you want to support:
add(Integer elem);
add(String elem);
But Object get() cannot be typed, such that it makes sense.
So finally you also can use Object with List, and omit the wrapper.
I don't think you can do it. String also is a final class and all that stuff. As #NimChimpsky said, you are probably better using Object itself. Another solution is a wrapper for both classes, but you will still have a resulting object which you will probably need to cast around and rely on instanceof:
class StringInt {
private String string;
private Integer integer;
public StringInt(String s) { this.string = s; }
public StringInt(Integer i) { this.integer = i; }
public Object getValue() { return string != null ? string : integer; }
}
Or with an ugly verification, which, obviously, will only apply at runtime...
class StringIntGen<T> {
private T t;
public StringIntGen(T t) {
if (!(t instanceof String) && !(t instanceof Integer))
throw new IllegalArgumentException(
"StringIntGen can only be Integer or String");
this.t = t;
}
public T getValue() { return t; }
}

Categories