My idea is that there is a validator interface, which has method getRealValue(). The return value depends on field, it could be String, Integer or Long values.
My chances are:
I can do assign return type as Object and use casting every time after I called this method. (RuntimeError if wrong casting happened).
I can use generic an pass return type to validator when instantiate it (and I still have to use casting but inside method getRealValue and only once). Still RuntimeError if I will forget to pass return type or pass wrong type.
If there is a way I can store return type inside validator and use it?
For your 1st point, there is no way around getting a ClassCastException at runtime in case of an inappropriate cast.
In your second case you won't need to cast, see example here:
public interface Foo<T> {
public T getValue();
}
... then somewhere else:
public class Blah<T> implements Foo<T> {
@Override
public T getValue() {
// TODO write the code
// note that because of type erasure you won't know what type T is here
return null;
}
}
... then, somewhere else:
Blah blah1 = new Blah<String>();
String s = blah1.getValue();
Blah blah2 = new Blah<Long>();
// etc.
Finally, here's some literature for you:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With