generic을 사용하는 Class에서 T의 객체 생성 하기.

참고 : http://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java


You cannot create an instance of a type parameter. For example, the following code causes a compile-time error:
public static <E> void append(List<E> list) {
    E elem = new E();  // compile-time error
    list.add(elem);
}
As a workaround, you can create an object of a type parameter through reflection:
public static <E> void append(List<E> list, Class<E> cls) throws Exception {
    E elem = cls.newInstance();   // OK
    list.add(elem);
}
You can invoke the append method as follows:
List<String> ls = new ArrayList<>();
append(ls, String.class);

댓글

이 블로그의 인기 게시물

Spring Batch - JobParameters Default Value 만들기

Hsqldb Server 재기동 시 오류