开发者

How to create new variable in java dynamically

Is it possible to create new variables in java dynamically.

c开发者_运维问答lass A {
methodA(String variableName) {

      }
}

So if new method is called twice, 2 new variables should be newly added to this class?

Is it possible?


No. Have you considered storing a Map<String, Object> in the class instead? The keys in the map would be the "variable names" and the values in the map would be the logical variable names.

If you could give more information about what you're trying to achieve (from a high-level perspective) that would help.


No, this is not possible to do in Java.

The fields in a class is determined at compile time and can't be changed during runtime (except though sophisticated techniques such as class reloading though for instance JRebel). I would however not recommend doing this, unless you're writing some IDE for instance.


A class and its members are defined and then compiled to bytecode, so they cannot be readily modified at run-time. That said, there are a number of libraries out there, such as cglib, which provide runtime modification functionality. This page can tell you more: http://java-source.net/open-source/bytecode-libraries

(This is not to say that runtime modification is the right thing to do!)


In a good design, a class must represent something, semantically speaking. You design it to represent an object in your system.

If you want to add more things to a design in run-time, well, something's not quite right -- unless, of course, the design needs adding information in run-time, and there are tons of data structures just ready for the job!

Check out Maps in Java, for example.


Following is the way that i have implemented and helped me to fix my solution easily without much hurdles.

// Creating the array List

List accountList = new ArrayList(); 




for(int k=0;k < counter;k++){
        accountList.add(k, (String)flowCtx.getValueAt("transitId"+m));
}

Iterating the loop and adding the objects into the arraylist with the index.

//Retrieving the object at run time with the help of the index

String a = accountList.get(i));


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

class Staff {
    private HashMap<String, Object> mylist = new HashMap<String, Object>() ;

    void setNewVar(String s, Object o) {
        mylist .put(s, o);
    }

    HashMap<String, Object> 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜