0

Sorry for the oddly worded question, but I was wondering how I would get a string and use that to create a new object. So I have over 100 Problems and if i want to run, say, problem 57 I do Problem p = new p57(); and then p.run() for the solution. I want to take a user input that and then using that do that problem .run() without having to create over 100 Problems

2

3 Answers 3

4

Get a Class instance with Class.forName(). You can create a new object of that class with Class.newInstance().

String className = String.format("org.example.problem.P%d", 57);
Class<Problem> clazz = (Class<Problem>) Class.forName(className);
Problem problem = clazz.newInstance();
problem.run();
Sign up to request clarification or add additional context in comments.

2 Comments

I replaced clazz with Class. And I'm getting an error: " non-static method newInstance() cannot be referenced from a static context"
Don't replace it! clazz is an instance of Class. Class.newInstance() is a non static method and should be called on an object (in this case on clazz).
1

You should use Reflection concept to do so

Class.forName(className);

Comments

0
Class c = Class.forName(name);
c.newInstance();

If the names are "normalized", e.g., they're numbered like you say they are, this is trivial.

You could either use introspection to run the method if they don't implement an interface, otherwise you can just call the interface method on the instance you've created.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.