Check type of primitive field

时光总嘲笑我的痴心妄想 提交于 2019-11-28 06:12:06
mP.

You're using the wrong constant to check for Long primitives - use Long.TYPE, each other primitive type can be found with a similarly named constant on the wrapper. eg: Byte.TYPE, Character.TYPE, etc.

o.getClass().getField("fieldName").getType().isPrimitive();

You can just use

boolean.class
byte.class
char.class
short.class
int.class
long.class
float.class
double.class
void.class

If you are using reflection, why do you care, why do this check at all. The get/set methods always use objects so you don't need to know if the field is a primitive type (unless you try to set a primitive type to the null value.)

In fact, for the method get() you don't need to know which type it is. You can do

// any number type is fine.
Number n = field.get(object);
long l = n.longValue();

If you are not sure if it is a Number type you can do

Object o = field.get(object); // will always be an Object or null.
if (o instanceof Number) {
     Number n = (Number) o;
     long l = n.longValue();
ahmed hamdy
  • To detect fields with long type use long.class or Long.TYPE.

  • To detect fields with Long type use Long.class.

Example:

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
    }
}

Notice:

Long.TYPE is static Constant member and is equivalent to long.class.

snippet code form 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();

Also check for answer for Difference between Integer.class and Integer.TYPE question

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!