简体   繁体   English

检查类是否具有关联的基元类型

[英]Checking if a class has an associated primitive type

Is there an easy way to detect whether a Class such as Integer or Long has an associated primitive type? 有没有一种简单的方法可以检测诸如Integer或Long之类的类是否具有关联的基元类型? (eg int and long respectively) (例如分别为int和long)

And by easy I don't mean something like maintaining a collection of Classes and checking if that class lives in the collection. 简单来说,我并不是说维护一个Classes集合并检查该类是否存在于集合中。

And by easy I don't mean something like maintaining a collection of Classes and checking if that class lives in the collection. 简单来说,我并不是说维护一个Classes集合并检查该类是否存在于集合中。

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. Java有固定数量的原始类型(7,如果我还记得它们的话),每个类型都只对应一个类。 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. 检查7个元素数组的成员资格非常快速和容易,或者您可以将它们放入Set并使用它来检查O(1)时间内的成员资格。 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. 如果您要问Java是否有内置方法(在标准API中)来执行此操作,我不这么认为。 But if there were one, it would probably just check for membership in that set or array of 7 elements. 但如果有一个,它可能只是检查该集合或7个元素的数组的成员资格。

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(): 反过来很容易,Class.isPrimitive():

Determines if the specified Class object represents a primitive type. 确定指定的Class对象是否表示基本类型。

There are nine predefined Class objects to represent the eight primitive types and void. 有九个预定义的Class对象来表示八种基本类型和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. 它们由Java虚拟机创建,并且与它们表示的基本类型具有相同的名称,即boolean,byte,char,short,int,long,float和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. 这些对象只能通过以下公共静态final变量访问,并且是此方法返回true的唯一Class对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM