Check type of primitive field

后端 未结 4 1505
野性不改
野性不改 2020-12-02 22:29

I\'m trying to determine the type of a field on an object. I don\'t know the type of the object when it is passed to me but I need to find fields which are long

4条回答
  •  既然无缘
    2020-12-02 22:41

    • 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 TYPE
            = (Class) long[].class.getComponentType();
    

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

提交回复
热议问题