How can I instantiate a class without calling the constructor of this class?

There are several cases where we can create an instance without calling the constructor of the instance class. Any ideas what these cases are (Non Reflection API)?

+4
source share
4 answers

Here's a surefire way to crack your system, but at least it won’t call the constructor . UseUnsafe#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 default constructor has Examplenot been called.

+5
source

Two "common" cases associated with the creation of objects based on a non-constructor, this deserializationand clone().

+4
source

, , JNI.

, . .

JNI AllocObject, , .

EDIT: clone() , .

+1

4

1) new -

2) serialization/deserialization - Serializable;

3) clone() - Cloneable

4) Through reflection. You can access the constructor and instantiate without using a new keyword. The best thing about Reflection is that it can be used to create objects for private constructors, provided that one does not work with the SecurityManager

0
source

All Articles