简体   繁体   English

如何通过名称将对象强制转换为类

[英]How to cast an object to a class by its name

I have an Object which is actually String Long or Integer. 我有一个实际上是String Long或Integer的Object。 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 错误:不兼容的类型:对象无法转换为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>以便编译器知道您所指的是哪个类

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. 如果您可以将逻辑更改为不需要传递Object和转换(例如泛型),那么它会更好。 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 ). 如果没有,我建议至少在使用instanceof进行转换之前确保Object属于该类型(如kocko的回答所示)。

Use the instanceof operator: 使用instanceof运算符:

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

This will make your code work, however if I were you, I would think about some refactoring, as this breaks the Open/Closed principle 这将使你的代码工作,但如果我是你,我会考虑一些重构,因为这打破了开放/封闭原则

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM