【问题标题】:Edit Classes in Runtime在运行时编辑类
【发布时间】:2013-05-31 21:25:24
【问题描述】:

我的程序读取了一个包含 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

【问题讨论】:

  • Builder 设计模式是一个不错的选择。它处理具有一些必需参数和一些可选参数的对象。

标签: java class runtime edit


【解决方案1】:

所以我想知道是否可以在运行时向类添加更多变量

没有。在 Java 中,您不能将新变量插入到已编译的程序中。 如果您不确定如何获取参数(及其类型),请尝试将它们存储在 Collection 中(例如,HashMap&lt;Long, Object&gt;)。

    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

【讨论】:

  • 谢谢!我想我对这个问题采取了不同的方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-16
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多