Creating an instance using the class name and calling constructor

前端 未结 10 2300
醉话见心
醉话见心 2020-11-22 05:51

Is there a way to create an instance of a particular class given the class name (dynamic) and pass parameters to its constructor.

Something like:

Obj         


        
相关标签:
10条回答
  • 2020-11-22 06:31

    You can use reflections

    return Class.forName(className).getConstructor(String.class).newInstance(arg);
    
    0 讨论(0)
  • 2020-11-22 06:37

    Another helpful answer. How do I use getConstructor(params).newInstance(args)?

    return Class.forName(**complete classname**)
        .getConstructor(**here pass parameters passed in constructor**)
        .newInstance(**here pass arguments**);
    

    In my case, my class's constructor takes Webdriver as parameter, so used below code:

    return Class.forName("com.page.BillablePage")
        .getConstructor(WebDriver.class)
        .newInstance(this.driver);
    
    0 讨论(0)
  • 2020-11-22 06:38

    If anyone is looking for a way to create an instance of a class despite the class following the Singleton Pattern, here is a way to do it.

    // Get Class instance
    Class<?> clazz = Class.forName("myPackage.MyClass");
    
    // Get the private constructor.
    Constructor<?> cons = clazz.getDeclaredConstructor();
    
    // Since it is private, make it accessible.
    cons.setAccessible(true);
    
    // Create new object. 
    Object obj = cons.newInstance();
    

    This only works for classes that implement singleton pattern using a private constructor.

    0 讨论(0)
  • 2020-11-22 06:39

    Yes, something like:

    Class<?> clazz = Class.forName(className);
    Constructor<?> ctor = clazz.getConstructor(String.class);
    Object object = ctor.newInstance(new Object[] { ctorArgument });
    

    That will only work for a single string parameter of course, but you can modify it pretty easily.

    Note that the class name has to be a fully-qualified one, i.e. including the namespace. For nested classes, you need to use a dollar (as that's what the compiler uses). For example:

    package foo;
    
    public class Outer
    {
        public static class Nested {}
    }
    

    To obtain the Class object for that, you'd need Class.forName("foo.Outer$Nested").

    0 讨论(0)
  • 2020-11-22 06:44

    You want to be using java.lang.reflect.Constructor.newInstance(Object...)

    0 讨论(0)
  • 2020-11-22 06:45

    If class has only one empty constructor (like Activity or Fragment etc, android classes):

    Class<?> myClass = Class.forName("com.example.MyClass");    
    Constructor<?> constructor = myClass.getConstructors()[0];
    
    0 讨论(0)
提交回复
热议问题