我正在尝试确定对象上字段的类型。我不知道传递给我的对象的类型,但我需要找到以下字段 longs。盒装的很容易区分 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.TYPE,对方基本类型可以用类似的命名在包装不断被发现。例如:Byte.TYPECharacter.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 班级

/**
 * The {@link Class} object that represents the primitive type {@code long}.
 */
@SuppressWarnings("unchecked")
public static final Class<Long> TYPE
        = (Class<Long>) long[].class.getComponentType();

还要检查 回答 为了 Integer.class 和 Integer.TYPE 之间的区别 问题

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top