如何通用地判断一个Java类是否为原始类型?

13

有没有一种方法可以判断一个类是否代表原始类型(是否存在不需要具体枚举所有原始类型的解决方案)?

注意:我已经看到了这个问题。我要求的基本上是相反的。我有这个类,我想知道它是否是一个原始类型。

3个回答

27

7

2

这个方法还会检查它是否是一个基本类型的包装器:

/**
* Checks first whether it is primitive and then whether it's wrapper is a primitive wrapper. Returns true
* if either is true
*
* @param c
* @return whether it's a primitive type itself or it's a wrapper for a primitive type
*/
public static boolean isPrimitive(Class c) {
  if (c.isPrimitive()) {
    return true;
  } else if (c == Byte.class
          || c == Short.class
          || c == Integer.class
          || c == Long.class
          || c == Float.class
          || c == Double.class
          || c == Boolean.class
          || c == Character.class) {
    return true;
  } else {
    return false;
  }

请使用Number.class.isAssignableFrom(c)代替检查所有Number子类型的相等性。 - digital illusion
@digitalillusion 这也包括非包装类型,比如 BigInteger,它也是一个 Number - kapex
return c.isPrimitive() || c.getSuperclass() == Number.class || c == Boolean.class || c == Character.class; 是一个更简单的解决方案。 - GV_FiQst

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接