Home > Blockchain >  How to use methods from another class, called by the client
How to use methods from another class, called by the client

Time:12-28

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

CodePudding user response:

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);

CodePudding user response:

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)

CodePudding user response:

I believe you should look into Class.forName and the reflection API in general. an earlier stackoverflow answer about the usage of Class.forName

  • Related