Java 将对象转换为特定数字类型的优雅方式 Map节点=Maps.newHashMap(); int courseId=((Number)node.get(“d”).intValue();

Java 将对象转换为特定数字类型的优雅方式 Map节点=Maps.newHashMap(); int courseId=((Number)node.get(“d”).intValue();,java,guava,Java,Guava,节点是一个包含键'd'的映射,相关值是一个short数字,上面的代码是将short转换为int的安全方法,但代码样式是痛苦的:( 我的问题:有没有更优雅的方法来处理这个问题,我搜索了“番石榴”lib,但没有找到任何相关内容 这里我更新了这个问题,原始数据是zookeeper节点上的一个json对象。反序列化后,它将值向上转换为对象,结果是Map如果您知道对象值实际上是Short,那么优雅/简洁的方法就是转换为Short: Map<String,Object> node = Map

节点是一个包含键
'd'
的映射,相关值是一个
short
数字,上面的代码是将
short
转换为
int
的安全方法,但代码样式是痛苦的:(

我的问题:有没有更优雅的方法来处理这个问题,我搜索了
“番石榴”
lib,但没有找到任何相关内容



这里我更新了这个问题,原始数据是zookeeper节点上的一个json对象。反序列化后,它将值向上转换为对象,结果是
Map

如果您知道
对象
值实际上是
Short
,那么优雅/简洁的方法就是转换为
Short

 Map<String,Object> node = Maps.newHashMap();
 int courseId = ((Number) node.get("d")).intValue();
short
->
int
是一种“加宽”转换,因为
int
具有更大的范围,因此不需要其他任何东西。并且,自动为您处理取消装箱


由于您正在将
对象
存储在
映射
,我看不出您可以如何避免强制转换。

您可以将映射的值从对象更新为数字吗

然后:

int courseId = (Short) node.get("d");
Map节点=Maps.newHashMap();
int courseId=node.get(“d”).intValue();

如果不只是像地图值那样短呢

这是一种通用的方法:

Map<String,Number> node = Maps.newHashMap();
int courseId = node.get("d").intValue();
@测试
public void test()引发异常{
Map node=newhashmap();
int courseInteger=popNumber(node.get(“d”);
//带整数的测试popNumber方法
int i=popNumber(5);
System.out.println(i);//输出5
//短波测试法
短s=popNumber(新短(“23”));
System.out.println(s);//输出23
//用长脉冲法测试pop数
长l=popNumber(2342L);
System.out.println(l);//输出2342
}
私有Num popNumber(对象o){
如果(o实例数)
返回(Num)o;
//如果您没有获得数字或其子项,则可以执行smth其他操作
//作为映射值,而不是返回null
返回null;
}

如果您想将数据作为int,为什么首先要使用shorts?如果您的映射包含shorts作为值,为什么它不是映射?首先,因为我可能需要考虑其他只接受整数的接口。其次,与配置映射一样,它可能包含String之类的值。为什么不使用JSON库来读取数据呢s JSON?例如()可以很好地实现这一点。例如
jsonObject.get(“d”).getAsInt();
我很想,但有时我得到的结果是
Object
你明白了我的意思。
Number
的转换不会引发“RuntimeException”。
@Test
public void test() throws Exception {
    Map<String, Object> node = new HashMap<>();
    int courseInteger = popNumber(node.get("d"));

    // test popNumber method with Integer
    int i = popNumber(5);
    System.out.println(i); // output 5

    // test popNumber method with Short
    short s = popNumber(new Short("23"));
    System.out.println(s); // output 23

    // test popNumber method with Long
    long l = popNumber(2342L);
    System.out.println(l); // output 2342
}

private <Num extends Number> Num popNumber(Object o) {
    if (o instanceof Number)
        return (Num) o;

    // you may do smth else if you get not Number or its child 
    // as map value rather to retur null
    return null;
}