Check type of primitive field

后端 未结 4 1509
野性不改
野性不改 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:50

    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();
    

提交回复
热议问题