1

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?

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244

2 Answers2

5

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

Primitives.isWrapperType(e.value().getClass())
Steven Schlansker
  • 37,580
  • 14
  • 81
  • 100
  • 1
    writing a 2-line method would do the same thing – Razvan Aug 15 '12 at 22:22
  • Huzzah for Guava, thanks, that's exactly what I needed! Much more elegant than a home-brewed solution. – dimo414 Aug 15 '12 at 22:27
  • Or you can just extract what you need here https://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/primitives/Primitives.java (but it's bad ^^) – Julien Lafont Aug 15 '12 at 22:31
  • Personally much cleaner to just use the library; fortunately, I already am, so it's an easy solution :) – dimo414 Aug 15 '12 at 22:36
1

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.

assylias
  • 321,522
  • 82
  • 660
  • 783