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

gowtham
  • 977
  • 7
  • 15
Sam
  • 405
  • 2
  • 5
  • 13

3 Answers3

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
1

You should use Reflection concept to do so

Class.forName(className);
ashokramcse
  • 2,841
  • 2
  • 19
  • 41
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.

Community
  • 1
  • 1
Dave Newton
  • 158,873
  • 26
  • 254
  • 302