Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an unconstructed object instance

Tags:

java

bytecode

In Java, is there any way to separate the steps that happen during object creation:

  • memory allocation
  • object construction

In other words, are there high level constructs (maybe using refection?) that accurately map the bytecode instructions new (memory allocation) and invokespecial (object construction).

No particular usage, more like a curiosity thing.

like image 853
Nick Avatar asked Jun 09 '13 19:06

Nick


2 Answers

No, there is no API (reflection or otherwise) for this in the JDK. You can however manipulate byte code itself, at runtime, using libraries that do that. For example, http://asm.ow2.org/

like image 145
Keith Avatar answered Oct 14 '22 00:10

Keith


     sun.misc.Unsafe

     /** Allocate an instance but do not run any constructor.
         Initializes the class if it has not yet been. */
     public native Object allocateInstance(Class cls)
         throws InstantiationException;

    ---- 

    Field f = Unsafe.class.getDeclaredField("theUnsafe");
    f.setAccessible(true);
    Unsafe unsafe = (Unsafe) f.get(null);

    Integer integer = (Integer)unsafe.allocateInstance(Integer.class);

    System.out.println(integer);  // prints "0"

don't know how to do the 2nd part - invoke constructor on it.

like image 25
ZhongYu Avatar answered Oct 13 '22 22:10

ZhongYu