Creating an instance using the class name and calling constructor

前端 未结 10 2356
醉话见心
醉话见心 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: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.

提交回复
热议问题