我的程序读取一个包含有关一个单元的 5 个参数的文件。 我已经使用这些参数建立了一个单元类,但是现在要求能够读取另一个文件,这个文件有 6 个参数,但这让我思考是否可以获得一个包含 10 个以上参数的文件,而我的单元类还没有准备好为了存储所有这些数据,所以我想知道是否可以在运行时向类添加更多变量。
示例
单元类别
public class Unit implements Serializable {
private String name;
private String unitId;
private byte year;
private String semester;
private String type;
private int credits;
public Unit(String name, String unitId, byte year, String semester, int credits) {
setName(name);
setUnitId(unitId);
setYear(year);
setSemester(semester);
setType(null);
setCredits(credits);
}
public Unit(String name, String unitId, byte year, String semester, String type, int credits) {
setName(name);
setUnitId(unitId);
setYear(year);
setSemester(semester);
setType(type);
setCredits(credits);
}
// Set's get's and all that stuff.
}
读取文件的示例代码
Scanner input = new Scanner(f);
ArrayList<Unit> units = new ArrayList();
while (input.hasNext()) {
String str = input.nextLine();
if (ignoreFirstLine) {
ignoreFirstLine = false;
} else {
String[] ArrayStr = str.split(";");
if(ArrayStr.length == 5){
Unit unit = new Unit(ArrayStr[0], ArrayStr[1], Byte.parseByte(ArrayStr[2]), ArrayStr[3], Integer.parseInt(ArrayStr[4]));
units.add(unit);
} else if (ArrayStr.length == 6){
Unit unit = new Unit(ArrayStr[0], ArrayStr[1], Byte.parseByte(ArrayStr[2]), ArrayStr[3], ArrayStr[4], Integer.parseInt(ArrayStr[5]));
units.add(unit);
} else {
//Modify classes in Runtime?
}
编辑:我的英语很棒:D
最佳答案
so i was wondering if i could add more variables to a class in runtime
没有。在 Java 中,您无法将新变量插入已编译的程序中。
如果您不确定如何获取参数(及其类型),请尝试将它们存储在集合中(例如 HashMap<Long, Object>
)。
else {
HashMap<Long, Object> map = new HashMap<>();
for(int i = 6; i < ArrayStr.length; i++)
//add items here
Unit unit = new Unit(ArrayStr[0],
ArrayStr[1],
Byte.parseByte(ArrayStr[2]),
ArrayStr[3],
ArrayStr[4],
Integer.parseInt(ArrayStr[5]),
map);
units.add(unit);
}
请注意,您必须更改 constructor
.
否则,你必须改变你的设计。你可以检查这个thread .
关于java - 在运行时编辑类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16935513/