I'm wondering if I can add code to an object variable and run it later?
I want to do something like this:
MyClass c = new MyClass();
c.addCode(
//Add my code here
);
c.runCode();
You want to run a task.
If you use Java 1.5 or more, take a look at java.util.concurrent package.
You'll find interfaces such as ExecutorService and Runnable which could help.
You would create instances of such Runnable classes to achieve what you want, with your "runCode" function being ExecutorService.execute()
You should define that code in a method inside your class and then call it whenever is neccessary. For example:
public class MyClass{
public MyClass(){ ... }
public void runCode(){
// Your code goes here
}
}
Then you can access your code as: c.runCode();
c without MyClass existing. What is your motivation behind getting rid of MyClass? Are you trying to do something like write code at runtime?If I'm interpenetrating your question correctly, it looks like you want to dynamically edit the source of your program while it's running? While not exactly impossible, it's extremely dangerous an unnecessary to do so.
You can avoid this with safe, proper use of control structures.
Just put the code you want to "add" inside a method:
//i want to add code to program
methodWithCode();
void methodWithCode(){
// code here
}
or inside a conditional statement.
if(i_want_to_add_code){
// code here
}