【问题标题】:Cast to a type dynamically according to the variable type in java根据java中的变量类型动态转换为类型
【发布时间】:2014-07-02 03:33:43
【问题描述】:

我有一个 HashMap 和一个名为 Plugin 的类,其中包含需要从我提到的映射映射的所有变量。 我只想根据在类中为该键声明的变量类型来转换键的值(在 Map 中)。 比方说,

--> 映射条目: . . 结果:“成功” . .

--> 插件类中的变量

private String result;

现在我想将键“结果”的值转换为插件类中变量结果的类型。 我尝试使用

this.result = this.result.getClass().cast(map.get("result"));

还有这个

this.result = (this.result.getClass())map.get("result");

谢谢

【问题讨论】:

标签: java casting


【解决方案1】:

实际上,由于早期绑定,这种“动态转换”在 Java 中是不可能的。编译器检查右侧的类型是否是左侧类型的子类型。

this.result.getClass() 返回Class 类型的变量,其值在编译器时未知,因此编译器不知道转换结果的类型,因此无法将转换结果分配给Plugin.result 字段。

您可能会因反射而变得混乱,但这不适合您的情况。

我建议你使用BeanUtils.populate(Plugin pligin, Map map)来转移你的财产。

另见java: how can i do dynamic casting of a variable from one type to another?

【讨论】:

    【解决方案2】:

    就像呼吸一样简单:

    result = (String) map.get("result");
    

    或者

    result = map.get("result").toString();
    

    【讨论】:

    • 我想在投射时去掉类名。我想让它通用,这样我就不需要更改转换函数。在这里,如果我将结果类型更改为整数,那么我也需要更改代码。
    • 祝你冒险愉快
    猜你喜欢
    • 1970-01-01
    • 2020-06-18
    • 1970-01-01
    • 2020-04-19
    • 2021-07-13
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多