有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在运行时编辑类

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


共 (1) 个答案

  1. # 1 楼答案

    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