Brandon oubiub
Brandon oubiub

Reputation: 311

Java Using Strings as Code

Okay, so, here's what I have in code:

public void makeObject(int i){
    String s = getString(i); //This returns the name of a class
    new s(); //This is what I want to do
}

Can I do this?

Upvotes: 1

Views: 141

Answers (1)

Roy T.
Roy T.

Reputation: 9638

No you can't do this, but what you're probably looking for is called 'reflection'.

Look at these series of (free) slides: http://www.slideshare.net/CiaranMcHale/java-reflection-explained-simply especially slide 11, but read the ones before that as well. It will give you an idea of what reflection is and a way to make a class by knowing the name (as a string) and how to instantiate a new instance of that class.

You can also find methods and fields by name, you can even modify existing classes in code.

Edit: for example the following code will return a class by string name

Class cls = Class.ForName("MyPackage.MyClassName");
return cls.NewInstance();

Upvotes: 9

Related Questions