我有一个像下面这样的对象的自定义类:
public class StudentState implements Serializable {
private static final long serialVersionUID = -3001666080405760977L;
public CourseState CourseState;
public class CourseState implements Serializable {
private static final long serialVersionUID = -631172412478493444L;
public List<Lessonstates> lessonstates;
}
public class Lessonstates implements Serializable {
private static final long serialVersionUID = -5209770078710286360L;
public int state;
}
}
现在我想在我的代码中初始化Lessonstates以使用它。我做到了这一点,但它有一个错误:
CourseState state = test.new CourseState();
Lessonstates newLesson = state.new Lessonstates();
我也试过这个:
Lessonstates newLesson = new CourseState().new Lessonstates();
错误是StudentState.CourseState.Lessonstates无法解析为某个类型 有没有人可以帮我解决这个问题?
答案 0 :(得分:3)
这很简单:
CourseState state = new CourseState();
state.lessonstates = new ArrayList<Lessonstates>();
对象需要先分配才能访问它们。分配后,您可以使用.
(点)符号
答案 1 :(得分:1)
您只需要从Lessonstates
实例化StudentState
,与CourseState
相同:
StudentState test = new StudentState();
CourseState state = test.new CourseState();
Lessonstates newLesson = test.new Lessonstates();
由于CourseState
和Lessonstates
都是StudentState
的内部类。
否则,你可以从StudentState
中取出我们的内部类,或者使它们成为静态的,以便能够在没有StudentState
实例的情况下实例化它们。