Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast an object to a class by its name

Tags:

java

casting

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

like image 616
guy Avatar asked Mar 15 '23 07:03

guy


1 Answers

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).

like image 75
m0skit0 Avatar answered Mar 27 '23 22:03

m0skit0