NoSuchFieldException when a field exists

I get java.lang.NoSuchFieldException when I try to run the following method:

  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); } 

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

I do not 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 just learned how to use reflection, so I'm sure this is some kind of syntax error ...

+64
java reflection
Mar 14 '13 at 21:56
source share
5 answers

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

+145
Mar 14 '13 at 22:00
source share

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

+11
Mar 14 '13 at 22:00
source share

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

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 length of the column annotation

 HelloWorld.class.getDeclaredField(propertyName).getAnnotation(Column.class).length() 
+6
May 7 '14 at 7:59
source share

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 be caused by the fact that caches are not synchronized in Android Studio. Go to File> Invalid Cache / Restart ...

See this also

+1
Sep 13 '16 at 9:47
source share

For all Android developers who see this who still cannot solve the problem, check to see if Proguard is turned on. If so, the class in question may be confused, and you will need to add rules to prevent this from happening.

0
Aug 30 '19 at 19:37
source share



All Articles