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)
...
Author by
shift66
Updated on June 05, 2022Comments
-
shift66 almost 2 years
I have
Field f = this.getClass().getFields()[0];
I need to know if
f
's value inthis
isnull
or not. There are many methods likegetInt()
andgetDouble()
, but I have not found a method likeObject getData()
orisNull()
. Is there such a method? -
shift66 over 12 yearsand what if it has a primitive type?
-
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 caseobject
is the targetBozho
meant above. -
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.