Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create an instance of class without invoking constructor of this class? [closed]

Tags:

java

There are some cases when we can create an instance without invoking a constructor of instance class. Any ideas what are these cases (Non Reflection API)?

like image 262
barbara Avatar asked Dec 14 '22 20:12

barbara


1 Answers

Here's a sure way to break your system, but at least it won't invoke the constructor. Use Unsafe#allocateInstance(Class)

import java.lang.reflect.Field;
import sun.misc.Unsafe;

public class Example {
    private String value = "42";
    public static void main(String[] args) throws Exception {
        Example instance = (Example) unsafe.allocateInstance(Example.class);
        System.out.println(instance.value);
    }

    static Unsafe unsafe;
    static {
        try {

            Field singleoneInstanceField = Unsafe.class.getDeclaredField("theUnsafe");
            singleoneInstanceField.setAccessible(true);
            unsafe = (Unsafe) singleoneInstanceField.get(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

which prints

null

indicating that the Example default constructor wasn't invoked.

like image 122
Sotirios Delimanolis Avatar answered Dec 17 '22 09:12

Sotirios Delimanolis