NoSuchFieldException when field exists

匿名 (未验证) 提交于 2019-12-03 02:05:01

问题:

I'm getting a java.lang.NoSuchFieldException when trying to run the following method:

 public void getTimes(String specialty, String day) {     ArrayList withSpec = new ArrayList();     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); } 

The error is on the line Time startTime = (Time)t.getClass().getField(day + "Start").get(t);

I don't understand this error, because monStart is a field of the Tutor class:

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; 

I'm just learning to use reflection, so I'm sure this is some sort of a syntactical error...

回答1:

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.



回答2:

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.



回答3:

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

Use getDeclaredField() instead of getField()

1)  String propertyName = "test";     Class.forName(this.getClass().getName()).getDeclaredField(propertyName); 

2) 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() 


回答4:

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



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