2010-01-11
どうしても型パラメータを取得したい。
こうすれば、取れない事もないのではないかと。。。
public class GetGenericsTest { @Test public void test() throws SecurityException, NoSuchFieldException, ClassNotFoundException { // 通常 Field field1 = TestBean1.class.getDeclaredField("value"); System.out.println(field1.getName() + "::" + field1.getType().getName()); Field field2 = TestBean2.class.getDeclaredField("list1"); System.out.println(field2.getName() + "::" + field2.getType().getName()); // ごりおし String string = field2.getGenericType().toString(); string = string.replaceAll("^.*\\<", "").replaceAll(">.*", ""); Class<?> clazz = Class.forName(string); System.out.println(clazz.getName()); } public static class TestBean1 { String value; } public static class TestBean2 { List<TestBean1> list1; } }
結果。
value::java.lang.String list::java.util.List imai78.GetGenericsTest$TestBean1
やっぱり何か違うかなあ。
追記
気になったので調べてみました。
以下のような感じで取得できます。
404 Not Found
というトラックバックを頂きました!早速書きなおしますと、、、
@Test
public void test2() throws SecurityException, NoSuchFieldException {
Field field2 = TestBean2.class.getDeclaredField("list1");
ParameterizedType paramType = (ParameterizedType) field2.getGenericType();
Type[] types = paramType.getActualTypeArguments();
for (Type type : types) {
Class<?> clz = (Class<?>) type;
System.out.println("type=" + clz.getName());
}
}
ナルホド、こっちの方が激しくスマートな感じがします><
トラックバック - http://d.hatena.ne.jp/imai78/20100111/1263208811
リンク元
- 69 http://d.hatena.ne.jp/kazuki-aranami/20100114/1263435522
- 10 http://reader.livedoor.com/reader/
- 5 http://twitter.com/imai78
- 5 http://www.google.co.jp/reader/view/feed/http://1.latest.misc-tools.appspot.com/f/dsah48qrh2903irbnnvfbnuil2r8hasdnlka23asdvc3k0fg54bv23fsd
- 4 http://www.google.co.jp/reader/view/?hl=ja&tab=wy
- 4 http://www.google.co.jp/reader/view/?tab=my
- 3 http://b.hatena.ne.jp/entry/d.hatena.ne.jp/imai78/20100111/1263208811
- 3 http://www.google.co.jp/search?client=firefox-a&rls=org.mozilla:ja:official&channel=s&hl=ja&source=hp&q=imai78&lr=&btnG=Google+検索
- 2 http://a.hatena.ne.jp/r-matuda/
- 2 http://b.hatena.ne.jp/entrylist/it?of=20






