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)?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With