[英]How can I generically tell if a Java Class is a primitive type?
Is there any way to take a Class and determine if it represents a primitive type (is there a solution that doesn't require specifically enumerating all the primitive types)? 有没有办法获取一个类并确定它是否代表一个原始类型(是否有一个解决方案不需要专门枚举所有原始类型)?
NOTE: I've seen this question . 注意:我已经看到了这个问题 。 I'm asking basically the opposite. 我问的基本上是相反的。 I have the Class, I want to know if it's a primitive. 我有班级,我想知道它是否是原始的。
Class对象上有一个名为isPrimitive的方法 。
Class.isPrimitive()会告诉你答案。
This method will also check whether it's a wrapper of a primitive type as well: 此方法还将检查它是否也是基本类型的包装:
/**
* 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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.