原语实例(包装器)

时间:2012-08-15 22:16:46

标签: java casting primitive-types

  

可能重复:
  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);
   }
}

除了通过逐个枚举所有原语之外,这是否可行?

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分:1)

您可以检查每个可能的原语,或者,如果您知道没有任何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的事实一致。