简体   繁体   中英

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

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.

涉及非基于构造函数的对象创建的两个“常见”案例是deserializationclone()

The only cases that I can imagine are serialization and JNI.

With serialization, you create a new object by deserializing the whole object state from an input stream. No constructor is invoked in this case.

With JNI, there is the AllocObject function, which allocates the space for a new object, also without calling a constructor.

EDIT: A call to clone() may be considered as another case, but this depends on how the method is implemented.

There are 4 ways of creating an instance of an Object

1) Through constructor using new keyword -The constructor should be accessible

2) Through serialization/deserialization -The class should be Serializable;

3) Through clone() method -The method should implement the marker interface Cloneable

4) Through reflection-You can access the constructor and create an instance without using the new keyword.The best thing about Reflection is that it can be used to instantiate Objects for private Constructors ,provided one does not mess up with SecurityManager

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM