获取java.util.List的泛型类型 [英] Get generic type of java.util.List

查看:971
本文介绍了获取java.util.List的泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有;

 列表< String> stringList = new ArrayList< String>(); 
列表<整数> integerList = new ArrayList< Integer>();

有没有一种(简单)的方法来检索列表的通用类型?

解决方案

如果这些实际上是某个类的字段,那么可以通过一些反射来获得它们:

  package test; 

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class Test {

List< String> stringList = new ArrayList< String>();
列表<整数> integerList = new ArrayList< Integer>();

public static void main(String ... args)throws Exception {
Field stringListField = Test.class.getDeclaredField(stringList);
ParameterizedType stringListType =(ParameterizedType)stringListField.getGenericType();
Class<?> stringListClass =(Class<> stringListType.getActualTypeArguments()[0];
System.out.println(stringListClass); //类java.lang.String。

字段integerListField = Test.class.getDeclaredField(integerList);
ParameterizedType integerListType =(ParameterizedType)integerListField.getGenericType();
Class<?> integerListClass =(Class<> integerListType.getActualTypeArguments()[0];
System.out.println(integerListClass); //类java.lang.Integer。


$ / code $ / pre

你也可以为参数类型和返回类型如果他们在你需要了解他们的类/方法的相同范围内,那么就没有必要了解它们,因为你已经宣布他们自己。


I have;

List<String> stringList = new ArrayList<String>();
List<Integer> integerList = new ArrayList<Integer>();

Is there a (easy) way to retrieve the generic type of the list?

解决方案

If those are actually fields of a certain class, then you can get them with a little help of reflection:

package test;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;

public class Test {

    List<String> stringList = new ArrayList<String>();
    List<Integer> integerList = new ArrayList<Integer>();

    public static void main(String... args) throws Exception {
        Field stringListField = Test.class.getDeclaredField("stringList");
        ParameterizedType stringListType = (ParameterizedType) stringListField.getGenericType();
        Class<?> stringListClass = (Class<?>) stringListType.getActualTypeArguments()[0];
        System.out.println(stringListClass); // class java.lang.String.

        Field integerListField = Test.class.getDeclaredField("integerList");
        ParameterizedType integerListType = (ParameterizedType) integerListField.getGenericType();
        Class<?> integerListClass = (Class<?>) integerListType.getActualTypeArguments()[0];
        System.out.println(integerListClass); // class java.lang.Integer.
    }
}

You can also do that for parameter types and return type of methods.

But if they're inside the same scope of the class/method where you need to know about them, then there's no point of knowing them, because you already have declared them yourself.

这篇关于获取java.util.List的泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆