Some Bits in Few Pieces
Blog.Init(Work.Bits);
So here finally, I am with my new blog where in i plan to put the bits from the other half of my life ;)

To cut the story short, I am kicking off this with a simple yet amusing problem that i gave to my friends.

Question:

Given a class:

class ClassWithPrivateConstructor
{
private ClassWithPrivateConstructor() {}

public string toString() { return "Class With Private Constructor"; }
}

Give a method to create the object of the above class. Write the code for the class 'PrivateAccessor' that would create the object of this class, and then call the 'toString' method to print the name of the class.

Solution:

import java.lang.reflect.*;

class ClassWithPrivateConstructor
{
private ClassWithPrivateConstructor() { }

public String toString() { return "Class with Private Constructor"; }
}


class PrivateAccessor
{
public PrivateAccessor()
{
try
{
Class cls = Class.forName("ClassWithPrivateConstructor");
Constructor constructor = cls.getDeclaredConstructors()[0];
constructor.setAccessible(true);

ClassWithPrivateConstructor pc = (ClassWithPrivateConstructor)constructor.newInstance(new Object[0]);
System.out.println(pc);
}
catch (Throwable e)
{
System.err.println(e);
}
}

public static void main(String args[])
{
new PrivateAccessor();
}
}


Explanation:

The key here is the "setAccessible()" method defined in the Constructor Class. We can use Reflection and call this method on the constructor that has private access specifier to make it accessible from code outside the class. And hence allows us to create the object of the class.

The same functionality is also available with C#, in the same way we can use Reflection there to set the access and create the objects.