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
-
2Looks like stackoverflow.com/questions/2408789/…Akshat Singhal– Akshat Singhal2014-01-08 04:20:48 +00:00Commented Jan 8, 2014 at 4:20
-
you can do that, java reflection is useful!Rugal– Rugal2014-01-08 04:33:40 +00:00Commented Jan 8, 2014 at 4:33
Add a comment
|
3 Answers
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();
2 Comments
Sam
I replaced clazz with Class. And I'm getting an error: " non-static method newInstance() cannot be referenced from a static context"
Markus Malkusch
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).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.