尝试运行以下方法时,我收到了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;

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

最佳答案

getField 方法仅在它是public时才能找到该字段。您将需要改用 getDeclaredField 方法,该方法将找到直接在类上声明的任何字段,即使它不是public

10-02 06:19