0

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?

  • 1
    No, it's not possible. Even when you create the instance via reflection, the default constructor is invoked. – Eran Sep 10 '14 at 20:15
  • `Object myObject = null;` --> IS this what you would be looking for? – Laf Sep 10 '14 at 20:16
  • It might be possible with `sun.misc.Unsafe`. But in "normal" Java, it's not possible. – August Sep 10 '14 at 20:16
  • "an object reference for a java class" - the object should refer to the `class` or to be an `instance` of the class ? – Nir Alfasi Sep 10 '14 at 20:18
  • 1
    @Eran It is possible by using JNI. Check my answer for a reference. – maba Sep 10 '14 at 20:42
  • @Laf that's a `null` reference, it's not an object. – Luiggi Mendoza Sep 10 '14 at 20:55
  • Related: [what-are-all-the-different-ways-to-create-an-object-in-java](http://stackoverflow.com/questions/95419/what-are-all-the-different-ways-to-create-an-object-in-java) – Pshemo Jan 05 '15 at 15:32

4 Answers4

3

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
August
  • 12,410
  • 3
  • 35
  • 51
2

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.

maba
  • 47,113
  • 10
  • 108
  • 118
1

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.

gkrls
  • 2,618
  • 2
  • 15
  • 29
0

Not possible. Every class has a default constructor that calls its parent constructor super() which boils down to Java's Object Class.

brso05
  • 13,142
  • 2
  • 21
  • 40