Skip to content

Instantly share code, notes, and snippets.

@yuroyoro
Created January 20, 2011 07:09
Show Gist options
  • Save yuroyoro/787523 to your computer and use it in GitHub Desktop.
Save yuroyoro/787523 to your computer and use it in GitHub Desktop.
型パラメータTのインスタンスを無理矢理(ヤメテーッッ)生成する方法
public class GenericsTrick {
public static void main(String[] args){
try{
System.out.println(
(new GenericsTrick()).createInstance(new Foo[]{})
);
}catch(Throwable e){
e.printStackTrace();
}
}
public <T> T createInstance(T[] holder) throws InstantiationException, IllegalAccessException{
Class<?> actualTypeParamClass = holder.getClass().getComponentType();
System.out.println(actualTypeParamClass);
// コンストラクタに引数は渡せない。Constructor<T>を取ってくればできるが
return (T)actualTypeParamClass.newInstance();
}
}
class Foo {
public String toString(){
return "This is Foo Instance. " + super.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment