NoSuchFieldException when field exists

java, reflection

Solution

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`.

Problem

I'm getting a `java.lang.NoSuchFieldException` when trying 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 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...

Original source

Related problems