How can I access a private constructor of a class?

One way to bypass the restriction is to use reflections:

import java.lang.reflect.Constructor;

public class Example {
    public static void main(final String[] args) throws Exception {
        Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();
        constructor.setAccessible(true);
        Foo foo = constructor.newInstance();
        System.out.println(foo);
    }
}

class Foo {
    private Foo() {
        // private!
    }

    @Override
    public String toString() {
        return "I'm a Foo and I'm alright!";
    }
}

  • You can access it within the class itself (e.g. in a public static factory method)
  • If it's a nested class, you can access it from the enclosing class
  • Subject to appropriate permissions, you can access it with reflection

It's not really clear if any of these apply though - can you give more information?


This can be achieved using reflection.

Consider for a class Test, with a private constructor:

Constructor<?> constructor  = Test.class.getDeclaredConstructor(Context.class, String[].class);
Assert.assertTrue(Modifier.isPrivate(constructor.getModifiers()));
constructor.setAccessible(true);
Object instance = constructor.newInstance(context, (Object)new String[0]);

The very first question that is asked regarding Private Constructors in Interviews is,

Can we have Private constructor in a Class?

And sometimes the answer given by the candidate is, No we cannot have private constructors.

So I would like to say, Yes you can have private Constructors in a class.

It is no special thing, try to think it this way,

Private: anything private can be accessed from within the class only.

Constructor: a method which has same name as that of class and it is implicitly called when object of the class is created.

or you can say, to create an object you need to call its constructor, if constructor is not called then object cannot be instantiated.

It means, if we have a private constructor in a class then its objects can be instantiated within the class only. So in simpler words you can say, if the constructor is private then you will not be able to create its objects outside the class.

What's the benefit This concept can be implemented to achieve singleton object (it means only one object of the class can be created).

See the following code,

class MyClass{
    private static MyClass obj = new MyClass();

    private MyClass(){

    }

    public static MyClass getObject(){
        return obj;
    }
}
class Main{
    public static void main(String args[]){

        MyClass o = MyClass.getObject();
        //The above statement will return you the one and only object of MyClass


        //MyClass o = new MyClass();
        //Above statement (if compiled) will throw an error that you cannot access the constructor.

    }
}

Now the tricky part, why you were wrong, as already explained in other answers, you can bypass the restriction using Reflection.