Created
          January 20, 2011 07:09 
        
      - 
      
- 
        Save yuroyoro/787523 to your computer and use it in GitHub Desktop. 
    型パラメータTのインスタンスを無理矢理(ヤメテーッッ)生成する方法
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | 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