Java: accessing private constructor with type parameters Java: accessing private constructor with type parameters java java

Java: accessing private constructor with type parameters


Make sure you use getDeclaredConstructors when getting the constructor and set its accessibility to true since its private.

Something like this should work.

Constructor<Foo> constructor= (Constructor<Foo>) Foo.class.getDeclaredConstructors()[0];constructor.setAccessible(true); Foo obj = constructor.newInstance("foo"); System.out.println(obj);

Update

If you want to make use of getDeclaredConstructor, pass Object.class as an argument which translates to a generic T.

Class fooClazz = Class.forName("path.to.package.Foo");Constructor<Foo> constructor = fooClazz.getDeclaredConstructor(Object.class);constructor.setAccessible(true); Foo obj = constructor.newInstance("foo"); System.out.println(obj);


you would need to get the class, find the constructor which takes a single argument with the lower bound of T (in this case Object), force the constructor to be accessible (using the setAccessible method), and finally invoke it with the desired argument.


Well in case if private constructor does not take any argument then we fetch problem while creating new instance, in this case after setAccessible true we can't create object.Even construct.newInstance(null); won't create object for no argument constructor.

can we create object of below code using reflection:

public class Singleton {    private static Singleton instance = new Singleton();    /* private constructor */    private Singleton() {}    public static Singleton getDefaultInstance() {        return instance;    }}

Yes we can create the object of above class.

// reflection concept to get constructor of a Singleton class.  Constructor<Singleton> constructor = Singleton.class.getDeclaredConstructor();// change the accessibility of constructor for outside a class object creation.  constructor.setAccessible(true);// creates object of a class as constructor is accessible now.  Singleton secondOb = constructor.newInstance();// close the accessibility of a constructor.constructor.setAccessible(false);

You can Refer: Example 2: "Eager Initialization" and "Singleton Violation by reflection" of my blog: http://sanjaymadnani.wordpress.com/2014/04/14/singleton-design-pattern-in-java/