????????????????
???????????????????????У?Initialization-on-demand holder ??????????????????????????μ????????
???????????????????????????????????????????????????????????????getInstance()????????ε???????????????????????????????????????????????????????????????????????????????????£?
????public class FooSingleton4 {
????private FooSingleton4() {
????}
????public static FooSingleton4 getInstance() {
????return FooSingleton4Holder.INSTANCE;
????}
????private static class FooSingleton4Holder {
????private static final FooSingleton4 INSTANCE = new FooSingleton4();
????}
????}
?????С?????л?
???????????????????л?????????????????в??????????????????????transient???????????????л????????????????readResolve()???????????INSTANCE?????á?
???????
????????????????????INSTANCE????????
????public enum FooEnumSingleton {
????INSTANCE;
????public static FooEnumSingleton getInstance() { return INSTANCE; }
????public void bar() { }
????}
????????Java????淶8.9??“Enum??final????????????????????????????????????л???????????????л?????????????????????????÷??????????????????????????????棬????????????????????????????????????”
??????????????????????????????л?????????????????????ο?????λ?????????????????????????′?????????????Щ?????????????
Constructor con = FooEnumSingleton.class.getDeclaredConstructors()[0];
Method[] methods = con.getClass().getDeclaredMethods();
for (Method method : methods) {
if (method.getName().equals("acquireConstructorAccessor")) {
method.setAccessible(true);
method.invoke(con?? new Object[0]);
}
}
Field[] fields = con.getClass().getDeclaredFields();
Object ca = null;
for (Field field : fields) {
if (field.getName().equals("constructorAccessor")) {
field.setAccessible(true);
ca = field.get(con);
}
}
Method method = ca.getClass().getMethod("newInstance"?? new Class[]{Object[].class});
method.setAccessible(true);
FooEnumSingleton spuriousEnum = (FooEnumSingleton) method.invoke(ca?? new Object[]{new Object[]{"SPURIOUS_INSTANCE"?? 1}});
printInfo(FooEnumSingleton.INSTANCE);
printInfo(spuriousEnum);
}
private static void printInfo(FooEnumSingleton e) {
System.out.println(e.getClass() + ":" + e.name() + ":" + e.ordinal());
}
?????????δ???????????
????class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:INSTANCE:0
????class com.blogspot.minborgsjavapot.singleton.FooEnumSingleton:SPURIOUS_INSTANCE:1
??????????????????????????????У??????????????java.lang.Enum????????????????У?????ο????????????н???????????mixin pattern????
??????????????????????????????“??????dualton??”??“??????tringleton??”???????????μ??????????ɡ????磬????????????????????????????????????????Ρ?
????????
???????????????????Щ??????????????????????????????????????????и????????????????
?????????????????????????Ч??????????????м?л???????????????????????????????