0

for example, i have 10 classes created with some methods in it. now, i want to create a method which takes one of these classname as input parameter in String format and instantiate that class.

public void instantiateclass(String Classname)
{

// this method should instantiate the given classname

 }

is this possible in java reflection? or any other concepts in java?

Jonathon Reinhart
  • 132,704
  • 33
  • 254
  • 328
Suresh
  • 1
  • Does this answer your question? [Creating an instance using the class name and calling constructor](https://stackoverflow.com/questions/6094575/creating-an-instance-using-the-class-name-and-calling-constructor) – Jonathon Reinhart May 31 '21 at 16:39
  • this worked Jonathon..Thanks – Suresh May 31 '21 at 17:49

2 Answers2

1

Yes, you can do that. you can change your method to return an Object.

public Object instantiateClass(Class<?> clazz)
{
    Object instance = null;
    try {
        instance = clazz.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | NoSuchMethodException | SecurityException e) {
        e.printStackTrace();
    }
    return instance;
}
Zeuzif
  • 318
  • 2
  • 14
-3

This can be easily done in c# by below code

private static object CreateInstanceByClassName(string className)
{
  var assembly = Assembly.GetExecutingAssembly();

  var type = assembly.GetTypes()
    .First(t => t.Name == className);

  return Activator.CreateInstance(type);
 }

Above code assumes that the class is present in same assemble