변경할 수있는 맵 객체가있는 라이브러리에서 일부 Java 객체를 필드로 가져옵니다. Collections.unmodifiableMap() 메서드로지도 객체를 래핑하여 런타임에만 해당 객체 필드를 읽는 방법이 필요합니다. 나는 자바 리플렉션 API를 사용하여 아래의 방법을 시도하지만 현장에서 실제지도 인스턴스를 얻기에 붙어 :반영을 사용하여 런타임에 Java Bean의 변경 가능 필드를 불변으로 만드는 방법
public static <T>T freeze(T obj){
if(obj!=null){
Field[] fields=obj.getClass().getDeclaredFields();
for(Field field:fields){
if(field.getType().equals(Map.class)){
//How to wrap a Map instance from the field in Collections.unmodifiableMap() object
}
}
}
return obj;
}
편집 --------------- -------------------------------------------------- -------------------------------------------------- ---------- java.util.Date 객체를 래핑하고 모든 변경 가능한 작업을 비활성화하는 Immutable Date 클래스를 작성했습니다. 이 래퍼를 사용하면 Collections.unmodifiableCollection()과 비슷한 기능을 사용할 수 있습니다.
final class DateUtil{
private DateUtil(){}
/**
*
* @param date
* @return Date
*
* This method will return an unmodifiable Date object.
*
*/
public static Date unmodifiableDate(Date date){
if(date==null){
throw new IllegalArgumentException();
}
return new ImmutableDate(new Date(date.getTime()));
}
/**
* This Date sub-class will override all the mutable Date operations
* and throw UnsupportedOperationException.
*/
private final static class ImmutableDate extends Date{
private static final long serialVersionUID = -1869574656923004097L;
private final Date date;
ImmutableDate(Date date){
this.date=date;
}
@Override
public void setTime(long date) {
throw new UnsupportedOperationException();
}
@Override
public void setDate(int date) {
throw new UnsupportedOperationException();
}
@Override
public void setHours(int hours) {
throw new UnsupportedOperationException();
}
@Override
public void setMinutes(int minutes) {
throw new UnsupportedOperationException();
}
@Override
public void setSeconds(int seconds) {
throw new UnsupportedOperationException();
}
@Override
public void setYear(int year) {
throw new UnsupportedOperationException();
}
@Override
public void setMonth(int month) {
throw new UnsupportedOperationException();
}
@Override
public Object clone() {
throw new UnsupportedOperationException();
}
}
}
감사합니다. 이 메소드를 호출 한 후 키를 변경/추가하려고하면 java.lang.UnsupportedOperationException이 throw됩니다. –
java.util.Date 필드에서이 작업을 수행 할 수 있습니까? 또한 동적으로 필드를 동적으로 만들 수 있습니까? –
아, 불행히도 Java에서는 Collections.unmodifiableMap이 java.util.Map 클래스 (필자가 아는 한) 용으로 java.util.Date의 불변 유형이 없습니다. 'final'은 소스 코드에서 변수의 재 할당을 방지하면서 컴파일 타임을위한 언어 기능이기 때문에 최종 수정자가 도움이 될지 확신 할 수 없습니다. 런타임에는 (거의) 아무것도 수행하지 않습니다. 그러나, 당신은 재미있는 문제가 있습니다 :) 나는 연구를 할 것이고 만약 내가 뭔가를 찾으면 당신과 나눌 것입니다. – Elka