3

Is it possible to create new variables in java dynamically.

class A {
methodA(String variableName) {

      }
}

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

Is it possible?

ihavprobs
  • 1,422
  • 8
  • 26
  • 41
  • 1
    The key is how do you plan to read them? You cannot reference them by name in your code, since they are created at runtime. – irreputable Apr 04 '11 at 10:57

6 Answers6

12

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I have a class that uses scheduled thread pool executor to schedule jobs. Through addJob(task), i will add this job. for every job that is scheduled, i need to store the scheduledFuture instance. So, i thought about creating variables dynamically. Is there any way to get this done without having compile-time variables? – ihavprobs Apr 04 '11 at 10:49
  • 1
    @shk: So it sounds like you want a `Map` in the end instead of a `Map`. – Jon Skeet Apr 04 '11 at 10:56
  • Exactly, i need the scheduled future instance. – ihavprobs Apr 04 '11 at 10:57
2

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.

aioobe
  • 413,195
  • 112
  • 811
  • 826
  • Is it possible using reflection to create variables? I thought we can only invoke methods dynamically using reflection; not create variables – ihavprobs Apr 04 '11 at 10:46
  • 2
    With the exception of reloading the class, there is no way to add a field to a class, not even through reflection. – aioobe Apr 04 '11 at 10:47
  • Even if you could do that, ... don't. – salezica Apr 04 '11 at 10:48
  • +1 - and even with bytecode engineering stuff (like JRebel), you end up with something that is a new class from the perspective of the type system. Existing instances of the old class will remain instances of the old class. – Stephen C Apr 04 '11 at 10:52
  • @Stephen C, ah, interesting, I had no idea about that. Is it because of different class loaders? – aioobe Apr 04 '11 at 11:02
  • Yes. See JLS 4.3.4. http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.4 – Stephen C Apr 04 '11 at 11:18
1

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!)

Ben
  • 7,548
  • 31
  • 45
1

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.

salezica
  • 74,081
  • 25
  • 105
  • 166
  • I said 'not quite' and 'general behaviour' man. Edited to be more explicit, so that nobody gets confused. That said, you're downvoting an explanation that addresses a bigger issue and offers much more information than a simple "no, you can't" because you doubt my Java skills? Come on. – salezica Apr 04 '11 at 10:50
  • @Stephen Bah, I'm sorry for that, it's 8.30 am here, I haven't slept all night, and I'm cranky. You're right, the reflection thing wasn't helping anyone. I don't know why my pride felt attacked. Edited out. – salezica Apr 04 '11 at 11:34
0

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.

Capensis
  • 113
  • 1
  • 9
0

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));
gmhk
  • 15,598
  • 27
  • 89
  • 112