How to create new variable in java dynamically

前端 未结 6 1252
闹比i
闹比i 2020-12-06 15:08

Is it possible to create new variables in java dynamically.

class A {
methodA(String variableName) {

      }
}

So if new method is called

6条回答
  •  清歌不尽
    2020-12-06 15:27

    Using a HashMap could be a solution. For example, if we have the following class:

    class Staff {
        private HashMap mylist = new HashMap() ;
    
        void setNewVar(String s, Object o) {
            mylist .put(s, o);
        }
    
        HashMap getVar() {
            return mylist;
        }
    }
    

    I can use it as:

    staff.setNewVar("NumVars",11);
    staff.setNewVar("NumBatches",300);
    ...
    

    and then:

    staff.getVar()
    

    wherever you need. I use it to convert some variables (the number can change) to JSON, successfully.

提交回复
热议问题