Kumar Avinash
Kumar Avinash

Reputation: 29

Creating an object reference for a java class without invoking it's constructor

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?

Upvotes: 0

Views: 1321

Answers (4)

maba
maba

Reputation: 48105

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.

Upvotes: 3

August
August

Reputation: 12568

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

Upvotes: 4

gkrls
gkrls

Reputation: 2664

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.

Upvotes: 1

brso05
brso05

Reputation: 13232

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

Upvotes: 0

Related Questions