Tuesday, December 18, 2007

Making an object without calling constructor?

Yes , thats possible in Java using the sun.reflect.ReflectionFactory
Just run this code and check out for yourself

import java.lang.reflect.*;
import java.io.Serializable;
import java.security.AccessController;
import sun.reflect.ReflectionFactory;

class Test2{
public Test2(){
System.out.println("Test 2");
}
}

class Test1 extends Test2{

int a;
public Test1(){
a=5;
System.out.println("Const Test1 "+a);
}
}

public class Test0 implements Serializable {

public Test0() {
System.out.println("Const Test0");
}

public static void main(String[] args) throws Exception {
Class c[]=new Class[0];
System.out.println(c==null);
System.out.println(Test1.class instanceof Class);
Constructor constr = reflectionFactory.newConstructorForSerialization(Test0.class, Test1.class.getConstructor(c));
Constructor constr1=Test1.class.getConstructor(new Class[0]);
System.out.println(constr.equals(constr1)+" "+constr.getName()+" "+constr1.getName() );
System.out.println(constr.getDeclaringClass().getName());
Test0 test=(Test0)constr.newInstance(new Object[0]);
System.out.println(constr.newInstance(new Object[0]).getClass());
}

private static final ReflectionFactory reflectionFactory = (ReflectionFactory)
AccessController.doPrivileged(
new ReflectionFactory.GetReflectionFactoryAction());

}