views:

183

answers:

6

I am java developer, went for an interview. I have been asked a question about the Private constructor

1) Can I access a Private Constructor of a Class and Instantiate the class.

I was thinking and gave the answer directly--- "NO" But its wrong, can any one help Why NO? and How we can achieve this

+16  A: 
  • 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?

Jon Skeet
A: 

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]);
tonio
I think you meant "reflection".
Joachim Sauer
Corrected "reflexivity" -> "reflection" .
sleske
Yes I checked, it works, thanks
harigm
+1  A: 

You can of course access the private constructor from other methods or constructors in the same class and its inner classes. Using reflection, you can also use the private constructor elsewhere, provided that the SecurityManager is not preventing you from doing so.

jarnbjo
+5  A: 

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(new Class[0]);
        constructor.setAccessible(true);
        Foo foo = constructor.newInstance(new Object[0]);
        System.out.println(foo);
    }
}

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

    @Override
    public String toString() {
        return "I'm a Foo and I'm alright!";
    }
}
Joachim Sauer
+1  A: 

Look at Singleton pattern. It uses private constructor.

3biga
Singleton uses the private contructor, outside the class we wont be instantiated, but we use already instantiated class
harigm
A: 

Well, you can also if there are any other public constructors. Just because the parameterless constructor is private doesn't mean you just can't instantiate the class.

devoured elysium