Take the 2-minute tour ×

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?

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

share|improve this question
add comment

marked as duplicate by Pangea, assylias, Mechanical snail, Taymon, Donal Fellows Aug 16 '12 at 21:08


2 Answers

up vote 5 down vote accepted

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

share|improve this answer
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 code.google.com/p/guava-libraries/source/browse/guava/src/com/… (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
add comment

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:


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.

share|improve this answer
What about booleans? –  jahroy Aug 15 '12 at 22:19
@jahroy good point - edited. –  assylias Aug 15 '12 at 22:21
add comment
