【问题标题】:instance of primative (wrapper) [duplicate]原始实例(包装器)[重复]
【发布时间】:2012-08-16 06:30:01
【问题描述】:

可能重复:
Determining if an Object is of primitive type

这可能听起来很愚蠢,但请原谅我,我正在使用愚蠢的代码。在给定对象集合的情况下,识别哪些是基元,或者更准确地说,是基元的包装器,最好的方法是什么?

假设我要打印所有图元:

HashMap<String,Object> context = GlobalStore.getContext(); // Some bizarre, strangely populated context
for(Entry<String,Object> e : context.entrySet()){
   if(e.value() instanceof PRIMITIVE){ // What goes here?
        System.out.println(e);
   }
}

除了一一列举所有原语之外,这可能吗?

【问题讨论】:

    标签: java casting primitive-types


    【解决方案1】:

    优秀的Google Guava 项目提供了一个Primitives.isWrapperType(Class),可以用作:

    Primitives.isWrapperType(e.value().getClass())
    

    【讨论】:

    • 写一个 2 行方法会做同样的事情
    • Guava 的 Huzzah,谢谢,这正是我所需要的!比自制解决方案优雅得多。
    • 或者你可以在这里提取你需要的东西code.google.com/p/guava-libraries/source/browse/guava/src/com/…(但这很糟糕^^)
    • 个人使用图书馆要干净得多;幸运的是,我已经是了,所以这是一个简单的解决方案:)
    【解决方案2】:

    您可以检查每个可能的原语,或者,如果您知道不会有任何 BigXxx 或 AtomicXxx,您也可以检查:

    if(e.value() instanceof Number || e.value() instanceof Boolean || e.value() instanceof Character)
    

    List of subclasses of Number:

    AtomicInteger, AtomicLong, BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short

    List of primitives:

    boolean、byte、short、int、long、char、float、double

    但考虑到只有 8 种原始类型,您不妨将它们全部检查并在实用程序方法中进行测试。

    ps:请注意,Guava 和可能重复中链接的答案也包括 Void,这与 System.out.println(void.class.isPrimitive()); 打印为 true 的事实一致。

    【讨论】:

      猜你喜欢
      • 2012-12-12
      • 1970-01-01
      • 2021-09-11
      • 1970-01-01
      • 1970-01-01
      • 2014-03-29
      • 2020-07-08
      • 1970-01-01
      • 2018-06-26
      相关资源
      最近更新 更多