instance of primative (wrapper) [duplicate]

﹥>﹥吖頭↗ 提交于 2019-12-24 06:59:09

问题


Possible Duplicate:
Determining if an Object is of primitive type

This may sound moronic, but please forgive me, I'm working with moronic code. What is the best way, given a collection of objects, to identify which are primitives, or more accurately, wrappers around primitives.

Suppose I want to print all primitives:

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);
   }
}

Is this possible, other than by enumerating all primitives one by one?


回答1:


The excellent Google Guava project provides a Primitives.isWrapperType(Class) which could be used as:

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



回答2:


You can either check each possible primitive, or, if you know that there won't be any BigXxx or AtomicXxx you can also check:

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

But considering that there are only 8 primitive types, you might as well check them all and put that test in a utility method.

ps: Note that Guava and the answers linked in the possible duplicate also include Void, which is consistent with the fact that System.out.println(void.class.isPrimitive()); prints true.



来源:https://stackoverflow.com/questions/11978139/instance-of-primative-wrapper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!