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
Asked
Active
Viewed 186 times
0
-
2Looks like http://stackoverflow.com/questions/2408789/getting-class-type-from-string – Akshat Singhal Jan 08 '14 at 04:20
-
you can do that, java reflection is useful! – Rugal Jan 08 '14 at 04:33
3 Answers
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();

Markus Malkusch
- 7,738
- 2
- 38
- 67
-
I replaced clazz with Class. And I'm getting an error: " non-static method newInstance() cannot be referenced from a static context" – Sam Jan 08 '14 at 16:29
-
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). – Markus Malkusch Jan 08 '14 at 16:33
0
Class c = Class.forName(name);
c.newInstance();
- http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#forName(java.lang.String)
- Creating an instance from String in Java
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.

Community
- 1
- 1

Dave Newton
- 158,873
- 26
- 254
- 302