![](/img/trans.png)
[英]How can I create an instance of class without invoking constructor of this class?
[英]How to create an instance of a class without invoking code of any of its constructors?
這是一個自我回答的問題,旨在分享一些來自http://java.dzone.com/articles/understanding-sunmiscunsafe的知識
我正在使用Oracle HotSpot Java虛擬機。
假設我有一個類A
並且想創建該類的實例而不調用其構造函數(可以說構造函數是私有的,昂貴的,或者只是做了我想避免的事情)。
例如如何創建此類的實例
class A{
private A(){
System.exit(0);//or any task I want to avoid
}
}
沒有退出我的應用程序? 可能嗎?
方法如下:
Field theUnsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
sun.misc.Unsafe unsafe = (sun.misc.Unsafe) theUnsafe.get(null);
A instance = (A)unsafe.allocateInstance(A.class);
System.out.println("done!");
建議不要使用sun
軟件包中的類。 這並不意味着您不能這樣做,所以要意識到這一點。
除了調用構造函數外,沒有其他方法可以做到。 即使使用反射,它也會在后台調用構造函數。 如果有辦法的話,像單例模式這樣的模式將不起作用。
如何在不使用構造函數的情況下創建實例?
你不知道 必須調用構造函數以使用Java創建實例。 但是您可以創建一個生成器或工廠方法來調用它。
// Factory method.
public static A makeIt() {
return new A();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.