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
source
share