반사 메커니즘 을 이용 하여 단 례 파괴 (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)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
JPA + QueryDSL 계층형 댓글, 대댓글 구현(2)이번엔 전편에 이어서 계층형 댓글, 대댓글을 다시 리팩토링해볼 예정이다. 이전 게시글에서는 계층형 댓글, 대댓글을 구현은 되었지만 N+1 문제가 있었다. 이번에는 그 N+1 문제를 해결해 볼 것이다. 위의 로직은 이...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.