How to test whether the value of a Java field gotten by reflection is null?

11,622

Solution 1

field.get(target) returns Object. So you can checkif (field.get(this) == null) {..}

If the field is primitive, it will get wrapped. int -> Integer, char -> Character, etc.

Solution 2

You need to get the field from the object then check if it is null

Field f = this.getClass().getFields()[0];
if (f.get(this) == null)
  ...
Share:
11,622
shift66
Author by

shift66

Updated on June 05, 2022

Comments

  • shift66
    shift66 almost 2 years

    I have

    Field f = this.getClass().getFields()[0];
    

    I need to know if f's value in this is null or not. There are many methods like getInt() and getDouble(), but I have not found a method like Object getData() or isNull(). Is there such a method?

  • shift66
    shift66 over 12 years
    and what if it has a primitive type?
  • Nom1fan
    Nom1fan over 4 years
    @stevemoretz No need to swear. target is the object the field belongs to. For example: SomeClass object = new SomeClass(); Field field = object.getDelcaredField("fieldName"); field.get(object); So in this case object is the target Bozho meant above.
  • Steve Moretz
    Steve Moretz over 4 years
    @Nom1fan That actually was a long time ago.I figured it out myself but anyway thanks.And that really wasn't a swear.sorry anyway.