2

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();

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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();

6 Comments

Well the point of having a varible is to get rid of the class alltogether
But the class must already exist for the variable to be declared. What do you want to use this for?
As Brian said, you can't instantiate c without MyClass existing. What is your motivation behind getting rid of MyClass? Are you trying to do something like write code at runtime?
It's for collision testing for entities in a small engine my friend and I are creating. we have the entity bot, and then you create Varibles of bot to add them to the screen.
and we want the entities to do specific things (eg, talk to you, run away) and we don't want to write class after class
|
0

I mean, if your variable type is, like, Queue<Runnable>, or internally has a Queue<Runnable>, then sure. You just add a new Runnable to the queue.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.