开发者

Checking if a class has an associated primitive type

开发者 https://www.devze.com 2023-01-10 00:31 出处:网络
Is there an easy way to detect whether a Class such as Integer or Long has an associated primit开发者_如何学Cive type? (e.g. int and long respectively)

Is there an easy way to detect whether a Class such as Integer or Long has an associated primit开发者_如何学Cive type? (e.g. int and long respectively)

And by easy I don't mean something like maintaining a collection of Classes and checking if that class lives in the collection.


And by easy I don't mean something like maintaining a collection of Classes and checking if that class lives in the collection.

But that is easy. Java has a fixed number of primitive types (7, if I remember them all) and each of those corresponds to exactly one class. It's very quick and easy to check for membership in an array of 7 elements, or you could put them in a Set and use that to check for membership in O(1) time. I'm not sure offhand which way would be quicker.

If you're asking whether Java has a built-in method (in the standard API) to do this, I don't think so. But if there were one, it would probably just check for membership in that set or array of 7 elements.


Yes, there is an easy way:

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
    }

then, create a helper method:

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

The reverse is very easy, Class.isPrimitive():

Determines if the specified Class object represents a primitive type.

There are nine predefined Class objects to represent the eight primitive types and void. These are created by the Java Virtual Machine, and have the same names as the primitive types that they represent, namely boolean, byte, char, short, int, long, float, and double.

These objects may only be accessed via the following public static final variables, and are the only Class objects for which this method returns true.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号