How to pass an object to a class by its name

I have an Object, which is actually a Long or Integer string. I want to pass it to the desired class, which I know by the parameter, and then compare the values. Now I am 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 that several objects are selected for the selected class.

I am wondering if there is a better way to do this, 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

Compilation Error:

error: incompatible types: object cannot be converted to Integer

I would like to know why this happens, also a solution for my code duplication

+4
source share
2 answers

Use Class<Integer>to let the compiler know which class you belong to

Class<Integer> c = java.lang.Integer.class;
Integer num2 = c.cast(myObject); // works now

, . , (, ), . , , , instanceof ( kocko answer).

+5

instanceof:

if (obj instanceof Float) {
    Float cast = (Float) obj;
} else if (obj instanceof String) {
    String cast = (String) obj;
} else if ..

, , , , Open/Closed

+2

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


All Articles