Primitive (wrapper) instance

Possible duplicate:
Determining if an object is a primitive type

This may sound silly, but please forgive me, I work with trendy code. What is the best way, given a set of objects, to determine which primitives, or rather, wrappers around primitives.

Suppose I want to print all the 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, with the exception of listing all the primitives one by one?

+1
source share
2 answers

An excellent Google Guava project provides Primitives.isWrapperType (class) , which can be used as:

 Primitives.isWrapperType(e.value().getClass()) 
+5
source

You can either check every possible primitive, or if you know that there will be no 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 can also check all of them and put this test in the utility method.

ps: Please note that Guava and answers related to a possible duplicate also include Void, which is consistent with the fact that System.out.println(void.class.isPrimitive()); outputs true.

+1
source

Source: https://habr.com/ru/post/973107/


All Articles