I have an Object which is actually String Long or Integer. I want to cast it to the right Class, which I know by parameter and then compare the values. Right now I'm doing:
switch(type) {
case Float:
(Float) obj ...
....
case Long:
(Long) obj ...
...
case String:
(String) obj ...
....
}
in each case the rest of the code is the same except casting a few objects to the specific class chosen.
I'm wondering if there is any better way to do it, so I tried the following:
Integer myInteger = 100;
Object myObject = myInteger;
Class c = java.lang.Integer.class;
Integer num1 = java.lang.Integer.class.cast(myObject); // works
Integer num2 = c.cast(myObject); // doesn't compile
Integer num3 = (java.lang.Integer) myObject; // works
the compilation error I get:
error: incompatible types: Object cannot be converted to Integer
I would like to know why it happens, also a solution for my code duplication
Use Class<Integer>
so compiler is aware of which class you're referring to
Class<Integer> c = java.lang.Integer.class;
Integer num2 = c.cast(myObject); // works now
On a side note, this kind of unsafe casting is highly not recommended. If you can change your logic to something that does not require passing an Object and casting (like generics for example), then it's better. If not, I suggest that at least you to make sure the Object is of that type before casting using instanceof
(as shown in kocko's answer).
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