I'm interested to know that, is it really possible to create an object reference for a java class without invoking any of it's constructors? If yes, how?
4 Answers
Definitely a bad idea, but you could use the sun.misc.Unsafe class to allocate an instance:
public static class TestClass {
int field = 1;
}
public static void main(String[] args) throws Exception {
Constructor<Unsafe> constructor = Unsafe.class.getDeclaredConstructor();
constructor.setAccessible(true);
Unsafe unsafe = constructor.newInstance();
TestClass test = (TestClass) unsafe.allocateInstance(TestClass.class);
System.out.println(test.field);
System.out.println(new TestClass().field);
}
Output:
0
1
Comments
It is possible by using JNI.
http://docs.oracle.com/javase/7/docs/technotes/guides/jni/spec/functions.html
Object Operations
AllocObject
jobject AllocObject(JNIEnv *env, jclass clazz);
Allocates a new Java object without invoking any of the constructors for the object. Returns a reference to the object.
The clazz argument must not refer to an array class.
It is hard to find any relevant usage of it. I would not use it but it is still an answer to the question.
Comments
The only way i can think of is using the clone() method
Object objectA = objectB.clone();
Now objectA.clone() != objectA and objectA and objectB point to two different places in memory so technically you create an object without calling its constructor.
1 Comment
Cloneable ?Not possible. Every class has a default constructor that calls its parent constructor super() which boils down to Java's Object Class.
Object myObject = null;--> IS this what you would be looking for?sun.misc.Unsafe. But in "normal" Java, it's not possible.classor to be aninstanceof the class ?