Dynamic casting in Java

Before I get a rebuke for not doing my homework, I couldn’t find any tips on a lot of questions about Java generics and dynamic casting.

The Scalar type 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;
}

Of course, this is usually discouraging. The reason I want such a method is because I have a collection of Scalars whose values ​​I would like to change later. However, as soon as they fall into the collection, their type type parameters are no longer available. Therefore, even if I want to make an assignment that fits perfectly at runtime, there is no way to know that it will 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 proven selection 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>        

}

,

this.value = (T) val;

ClassCastException?

+3
1

:

this.value.getClass().isAssignableFrom(val.getClass())

, , , , value null.

:

this.value = (T) val;

Number, T, T Number - . value Double, val Integer, .

, Class<T>. , Class<T> . ( , value , .) , ( ), :

T value = valueClass.cast(val);
+3

Source: https://habr.com/ru/post/1769667/


All Articles