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

半城伤御伤魂 提交于 2020-01-11 12:21:32

问题


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?


回答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.




回答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)
  ...



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/8228207/how-to-test-whether-the-value-of-a-java-field-gotten-by-reflection-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!