Checking if a class has an associated primitive type

Is there an easy way to determine if a class, such as Integer or Long, has a primitive type? (e.g. int and long respectively)

And I just do not mean something like supporting a collection of classes and checking if this class lives in the collection.

+3
source share
2 answers

And I just do not mean something like supporting a collection of classes and checking if this class lives in the collection.

But it is easy. Java has a fixed number of primitive types (7 if I remember them), and each of them corresponds to exactly one class. It’s very quick and easy to verify that you belong to an array of 7 elements, or you can put them in Setand use to verify membership in O (1) time. I'm not sure what will be faster.

, Java ( API), . , , , 7 .

+3

, :

public class ClassUtils {
    private static final Set<Class<?>> wrapperClasses = new HashSet<Class<?>>();
    static {
        wrapperClasses.add(Integer.class);
        ... there are a set number of wrapper classes - add them all here
    }

:

    public static boolean isWrapperForPrimitive(Class<?> klass) { 
        return wrapperClasses.contains(klass); 
    }
}

, Class.isPrimitive():

, .

void. Java , , , : boolean, byte, char, short, int, long, float double.

, true.

0

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


All Articles