字段存在时发生 NoSuchFieldException

当尝试运行以下方法时,我得到了 java.lang.NoSuchFieldException:

 public void getTimes(String specialty, String day) {
ArrayList<Tutor> withSpec = new ArrayList<Tutor>();
for (Tutor t : tutorList){
try {
Time startTime = (Time)t.getClass().getField(day + "Start").get(t);
} catch (NoSuchFieldException | SecurityException | IllegalAccessException ex) Logger.getLogger(DBHandler.class.getName()).log(Level.SEVERE, null, ex); }

错误在 Time startTime = (Time)t.getClass().getField(day + "Start").get(t);行上

我不明白这个错误,因为 monStart 是 Tutor类的一个字段:

Public class Tutor implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@NotNull
@Column(name = "tutorID")
private Integer tutorID;


....


@Column(name = "monStart")
@Temporal(TemporalType.TIME)
Date monStart;

我只是在学习使用反射,所以我肯定这是某种语法错误..。

87040 次浏览

The getField method will only find the field if it's public. You will need to use the getDeclaredField method instead, which will find any field that is declared directly on the class, even if it's not public.

According to the javadoc, Class.getField() "Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object". Use getDeclaredField() if you want to access non-public fields.

Best solutions for getClass().getField() problem are:

  1. Use getDeclaredField() instead of getField():
        String propertyName = "test";
Class.forName(this.getClass().getName()).getDeclaredField(propertyName);
  1. Replace "HelloWorld" with your class name:
        String propertyName = "name";
HelloWorld.class.getDeclaredField(propertyName);

If you want to get the annotation length of the column:

HelloWorld.class.getDeclaredField(propertyName).getAnnotation(Column.class).length();

I came to this question based on the title. I was getting the same error (NoSuchFieldException) in my Android project but for a different reason.

So for others who come here, this error can also potentially be caused by the caches getting out of sync in Android Studio. Go to File > Invalidate Caches / Restart...

See this also

For any Android developers seeing this that still can't seem to fix the issue, check to see if Proguard is enabled. If it is, it's possible the class in question is being obfuscated and you'll need to add rules to prevent that from happening.

Good to know... If you have a @Configuration on your class, getDeclaredFields() won't contains your fields.

As mentioned in the accepted answer, using getDeclaredField will potentially solve your problem (in case the field wasn't declared as public).

If you are still getting the NoSuchFieldException, then it might be because that field is actually in the superclass! Indeed, if your class extends another class, then you will not get the inherited fields through the getDeclaredField method. Here is how to fix that problem:

String propertyName = "foo";
yourClass.getClass().getSuperClass().getDeclaredField(propertyName);