0

I am making a program that lets the user call a class, like it takes a string input, then calls the run() method of that class, is there any way to do that? I was hoping something like:

String inp=new Scanner(System.in).nextLine();
Class cl=new Class(inp);
cl.run();

I know that the code isn't correct, but that is my main idea

30thh
  • 10,861
  • 6
  • 32
  • 42
dfmaaa1
  • 51
  • 7

2 Answers2

3

Creating and using a class by name requires some preconditions:

  • Full name of the class must be used, including package name.
  • You need to know the parameters of the constructor. Usually the no-arguments constructor is used for a such use case.
  • (Optional) You need an interface this class must implement which declares the method "run" (or any other methods you want to use).

An example with a subclass of Runnable:

    String className = "some.classname.comes.from.Client";

    Class<Runnable> clazz = (Class<Runnable>) Class.forName(className);
    Runnable instance = clazz.getConstructor().newInstance();
    instance.run();

If you don't have a common interface, you can invoke the method using reflection:

    Class<Object> clazz = (Class<Object>) Class.forName(className);
    Object instance = clazz.getConstructor().newInstance();
    clazz.getMethod("run").invoke(instance);

or using method with parameters:

    Integer p1 = 1;
    int p2 = 2;
    clazz.getMethod("methodWithParams", Integer.class, Integer.TYPE).invoke(instance, p1, p2);
30thh
  • 10,861
  • 6
  • 32
  • 42
0

String Variable can't be a reference for the Class. to to a something like changing the object depends on the input you can use polymorphism and design patterns (Factory Pattern)

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 27 '21 at 09:51