반사 메커니즘 을 이용 하여 단 례 파괴 (1)

2893 단어 Java
머리말
갑 작 스 러 운 기발 한 생각 이 들 었 습 니 다. 단일 클래스 는 사유 화 구조 함 수 를 통 해 단일 사례 를 실현 할 수 있 고 자바 에 서 는 반 사 를 통 해 클래스 의 임 의적 인 속성 과 방법 을 얻 을 수 있 습 니 다. 그러면 자바 반사 체 제 를 이용 하여 단일 클래스 의 사유 구조 함 수 를 얻어 대상 을 예화 시 켜 새로운 대상 을 얻 을 수 있 습 니 다.다음은 코드 로 실천 한다.
코드 구현
단일 클래스 Singleton:
public class Singleton {
    private static Singleton singleton ;

    private Singleton() {
    }

    public static Singleton getSingleton() {
        if (singleton == null) {
            synchronized (Singleton.class) {
                if (singleton == null) {
                    singleton = new Singleton();
                    return singleton;
                }
            }
        }
        return singleton;
    }
}

주 함수:
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //    getSingleton()      
        Singleton singleton1 = Singleton.getSingleton();
        //          
        Class singleton1Class = singleton1.getClass();
        Singleton singleton2 = null;
        Constructor> constructor = singleton1Class.getDeclaredConstructor();//    Class              ,       
        constructor.setAccessible(true);  //          (  ,      ,          )
        singleton2 = (Singleton) constructor.newInstance();//     
        if(singleton1==singleton2){
            System.out.println("  ");
        }else {
            System.out.println("   ");
        }
    }
}

출력:
   

반사 메커니즘 을 이용 하여 단 례 파괴 (2)

좋은 웹페이지 즐겨찾기