Program Tip

목록을 인스턴스화하는 방법

programtip 2020. 10. 27. 23:10
반응형

목록을 인스턴스화하는 방법?


이런 종류의 일을 어떻게 할 수 있습니까? 나는 확인할 수 (obj instanceof List<?>)있지만 그렇지 않은 경우 (obj instanceof List<MyType>). 이렇게 할 수있는 방법이 있습니까?


제네릭의 컴파일 시간에 데이터 유형이 삭제되기 때문에 불가능합니다. 이 작업을 수행 할 수있는 유일한 방법은 목록이 보유하는 유형을 보유하는 일종의 래퍼를 작성하는 것입니다.

public class GenericList <T> extends ArrayList<T>
{
     private Class<T> genericType;

     public GenericList(Class<T> c)
     {
          this.genericType = c;
     }

     public Class<T> getGenericType()
     {
          return genericType;
     }
}

if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object
}

확인할 유형을 얻으려면 리플렉션을 사용해야 할 것입니다. 목록의 유형을 가져 오려면 : java.util.List의 일반 유형 가져 오기


비어 있지 않은의 object인스턴스 를 확인하려는 경우 사용할 수 있습니다 List<T>.

if(object instanceof List){
    if(((List)object).size()>0 && (((List)object).get(0) instanceof MyObject)){
        // The object is of List<MyObject> and is not empty. Do something with it.
    }
}

Object의 List 또는 Map 값의 참조가 Collection의 인스턴스인지 확인하는 경우 필요한 List의 인스턴스를 만들고 해당 클래스를 가져옵니다.

Set<Object> setOfIntegers = new HashSet(Arrays.asList(2, 4, 5));
assetThat(setOfIntegers).instanceOf(new ArrayList<Integer>().getClass());

Set<Object> setOfStrings = new HashSet(Arrays.asList("my", "name", "is"));
assetThat(setOfStrings).instanceOf(new ArrayList<String>().getClass());

이것이 제네릭 (@Martijn의 대답)으로 래핑 될 수 없다면 중복 목록 반복을 피하기 위해 캐스팅하지 않고 전달하는 것이 좋습니다 (첫 번째 요소의 유형을 확인해도 아무것도 보장하지 않음). 목록을 반복하는 코드에서 각 요소를 캐스팅 할 수 있습니다.

Object attVal = jsonMap.get("attName");
List<Object> ls = new ArrayList<>();
if (attVal instanceof List) {
    ls.addAll((List) attVal);
} else {
    ls.add(attVal);
}

// far, far away ;)
for (Object item : ls) {
    if (item instanceof String) {
        System.out.println(item);
    } else {
        throw new RuntimeException("Wrong class ("+item .getClass()+") of "+item );
    }
}

instanceof를 사용하는 대신 가짜 팩토리를 사용하여 많은 메서드를 포함 할 수 있습니다.

public class Message1 implements YourInterface {
   List<YourObject1> list;
   Message1(List<YourObject1> l) {
       list = l;
   }
}

public class Message2 implements YourInterface {
   List<YourObject2> list;
   Message2(List<YourObject2> l) {
       list = l;
   }
}

public class FactoryMessage {
    public static List<YourInterface> getMessage(List<YourObject1> list) {
        return (List<YourInterface>) new Message1(list);
    }
    public static List<YourInterface> getMessage(List<YourObject2> list) {
        return (List<YourInterface>) new Message2(list);
    }
}

참고 URL : https://stackoverflow.com/questions/10108122/how-to-instanceof-listmytype

반응형