1

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?

3
  • Do you just want to create a new instance of an already-existing class? Then look at Class.forName which will return a Class. Commented Jun 25, 2011 at 7:45
  • 1
    Better suited to StackOverflow? Commented Jun 25, 2011 at 8:04
  • Why are you doing this? For sending messages across a network? Commented Jun 25, 2011 at 8:22

1 Answer 1

9

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();
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, haven't looked at it yet, but I think it is perfect by how you described it.

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.