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

前端 未结 4 1275
北恋
北恋 2021-01-15 16:42

I have

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

I need to know if f\'s value in this is null or not

相关标签:
4条回答
  • 2021-01-15 16:48

    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.

    0 讨论(0)
  • 2021-01-15 16:50

    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)
      ...
    
    0 讨论(0)
  • 2021-01-15 16:55

    You didn't search well enough: http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html#get%28java.lang.Object%29

    Call this method, and check if the returned object is null.

    0 讨论(0)
  • 2021-01-15 16:59

    use Object obj=f.get(this) and check whether the returned object(in this case obj) is null or not

    0 讨论(0)
提交回复
热议问题