[ACCEPTED]-How to create new variable in java dynamically-java

Accepted answer
Score: 12

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

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

Score: 2

No, this is not possible to do in Java.

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

Score: 1

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

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

Score: 1

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

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

Check out Maps in Java, for example.

Score: 0

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

// Creating the array 4 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 3 into the arraylist with the index.

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

String a = accountList.get(i));
Score: 0

Using a HashMap could be a solution. For 4 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 3 can use it as:


and then:


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

More Related questions