How can I access a private constructor of a class?

gmhk picture gmhk · Apr 8, 2010 · Viewed 78.3k times · Source

I am a Java developer. In an interview I was asked a question about private constructors:

Can you access a private constructor of a class and instantiate it?

I answered 'No' but was wrong.

Can you explain why I was wrong and give an example of instantiating an object with a private constructor?

Answer

Joachim Sauer picture Joachim Sauer · Apr 8, 2010

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!";
    }
}