Skip to content

Instantly share code, notes, and snippets.

@uemuraj
Created September 6, 2012 23:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uemuraj/3661369 to your computer and use it in GitHub Desktop.
Save uemuraj/3661369 to your computer and use it in GitHub Desktop.
ごくまれに必要になるジェネリックの形引数を調べる方法と、動的に任意の型の配列を作成する方法
import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* ジェネリックから配列の動的生成の例:
*/
public class GenericArray<T> {
@SuppressWarnings("unchecked")
public T[] newArray(int length) {
// 実際のインスタンスが、このクラスから派生されたものであり
// スーパークラス=このクラスが総称型であるとして型引数 <T> を取得しようと試みる
// 一般的には複数の型引数を指定できるため結果は配列になる
ParameterizedType type = (ParameterizedType) this.getClass().getGenericSuperclass();
Type[] types = type.getActualTypeArguments();
// このクラスの型引数 <T> の配列のインスタンスを作成する
// このクラスの型引数は1つなので最初の1つしか使わない
return (T[]) Array.newInstance((Class<T>) types[0], length);
}
// 無名のクラスでは動きません...
public static class SampleClazz extends GenericArray<String> {
}
public static void main(String[] args) {
SampleClazz sample = new SampleClazz();
String[] array = sample.newArray(10);
System.out.println(array.getClass());
}
}
@uemuraj
Copy link
Author

uemuraj commented Sep 6, 2012

こんな感じです...

Microsoft Windows XP Version 5.1.2600 Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\uemuraj>cd デスクトップ

C:\Documents and Settings\uemuraj\デスクトップ>java -version
java version "1.6.0_35"
Java(TM) SE Runtime Environment (build 1.6.0_35-b10)
Java HotSpot(TM) Client VM (build 20.10-b01, mixed mode, sharing)

C:\Documents and Settings\uemuraj\デスクトップ>javac GenericArray.java

C:\Documents and Settings\uemuraj\デスクトップ>java -classpath . GenericArray
class [Ljava.lang.String;

@uemuraj
Copy link
Author

uemuraj commented Sep 6, 2012

Microsoft Windows XP Version 5.1.2600 Copyright 1985-2001 Microsoft Corp.

C:\Documents and Settings\uemuraj>cd デスクトップ

C:\Documents and Settings\uemuraj\デスクトップ>java -version
java version "1.6.0_35"
Java(TM) SE Runtime Environment (build 1.6.0_35-b10)
Java HotSpot(TM) Client VM (build 20.10-b01, mixed mode, sharing)

C:\Documents and Settings\uemuraj\デスクトップ>javac GenericArray.java

C:\Documents and Settings\uemuraj\デスクトップ>java -classpath . GenericArray
class [Ljava.lang.String;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment