[英]Check type of primitive field
我正在嘗試確定對象上字段的類型。 當它傳遞給我時,我不知道對象的類型,但我需要找到long
的字段。 很容易區分盒裝Long
但原始long
似乎更難。
我可以確保傳遞給我的對象只有Longs
,而不是原語,但我寧願沒有。 所以我擁有的是:
for (Field f : o.getClass().getDeclaredFields()) {
Class<?> clazz = f.getType();
if (clazz.equals(Long.class)) {
// found one -- I don't get here for primitive longs
}
}
一種似乎有用的hacky方式是:
for (Field f : o.getClass().getDeclaredFields()) {
Class<?> clazz = f.getType();
if (clazz.equals(Long.class) || clazz.getName().equals("long")) {
// found one
}
}
如果有的話,我真的想要一個更干凈的方法。 如果沒有更好的方法,那么我認為要求我收到的對象只使用Long
(不long
)將是一個更好的API。
有任何想法嗎?
您正在使用錯誤的常量來檢查Long基元 - 使用Long.TYPE
,可以在包裝器上找到具有類似命名常量的其他基本類型。 例如: Byte.TYPE
, Character.TYPE
等
o.getClass().getField("fieldName").getType().isPrimitive();
你可以使用
boolean.class
byte.class
char.class
short.class
int.class
long.class
float.class
double.class
void.class
如果您正在使用反射,為什么要關心,為什么要進行此檢查。 get / set方法總是使用對象,因此您不需要知道該字段是否是基本類型(除非您嘗試將基本類型設置為空值。)
實際上,對於方法get(),您不需要知道它是哪種類型。 你可以做
// any number type is fine.
Number n = field.get(object);
long l = n.longValue();
如果您不確定它是否為數字類型,則可以執行此操作
Object o = field.get(object); // will always be an Object or null.
if (o instanceof Number) {
Number n = (Number) o;
long l = n.longValue();
要檢測long
類型的字段,請使用long.class
或Long.TYPE
。
要檢測Long
類型的字段,請使用Long.class
。
例:
for (Field f : o.getClass().getDeclaredFields()) {
Class<?> clazz = f.getType();
// to detect both Long and long types
if (Long.class.equals(clazz) || long.class.equals(clazz)) {
// found one
}
}
通知 :
Long.TYPE
是靜態常量成員,等同於long.class
。
代碼段表格Long
Class
/** * The {@link Class} object that represents the primitive type {@code long}. */ @SuppressWarnings("unchecked") public static final Class<Long> TYPE = (Class<Long>) long[].class.getComponentType();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.