0

How to create an instance of a particular class with class name (dynamic) and pass parameters to it's a function of class?

my pseudo code is :

String className = "login";
Class<?> clazz = Class.forName(className);
clazz.checkUserFunc(argument);

checkUserFunc Function is member of Login class

Mike Szyndel
  • 10,461
  • 10
  • 47
  • 63
user3187514
  • 11
  • 1
  • 2

2 Answers2

0

You can get an instance of the class constructor matching the give arguments with getConstructor.

Constructor<?> ctor=thisClass.getConstructor(<arguments>); // where arguments are the parameters expected by the constructor.

You can then create an instance of the class and call whatever methods you like with getDeclaredMethod.

getDeclaredMethod(String name, Class...<?> parameterTypes)
Simon
  • 14,407
  • 8
  • 46
  • 61
0

First, you have to create a new instance of your class:

Object o = clazz.newInstance();

Note: If your class does not have a default constructor, newInstance() will throw an exception. In that case, you must query the appropriate constructor from your class and call it. This only makes sense, if you have some kind of convention, e.g. the constructor must accept exactly on String argument or so (see Creating an instance using the class name and calling constructor). The easiest way is to require a default constructor, so the code above will work.

Then you can call any instance method of your object. Usually you should have another convention like the class must implement interface MyInterface. This makes calling your method easy:

MyInterface myObj = (MyInterface)o;
myObj.checkUserFunc(argument);
Community
  • 1
  • 1
isnot2bad
  • 24,105
  • 2
  • 29
  • 50