Creating an object reference for a java class without invoking it's constructor -
i'm interested know that, possible create object reference java class without invoking of it's constructors? if yes, how?
definitely bad idea, use sun.misc.unsafe
class allocate 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
Post a Comment