list 获取元素 java,获取List中元素的类型,其中List是java中方法的返回类型

I got every methods in my package using reflections and then based on the return type of every method, I want to do some operations.

But unfortunately I had a problem with collections. when I find a method in which return a collection like a List, I can't find a way to get to know about the type of List's element.

I used the code below to get the return type of my methods.

if (method.getReturnType().equals(List.class)){

statement;

}

The above code does work well and gets every method which return a List but it is just return java.util.List as a return type and I can't find a way to get to know about the type of element in that List.

For instance, if I have a method like this:

public List getCustomerModel(){

statement;

}

I don't know how can I get CmsCustomerModel class as a type of element for return List. I would be wonder if anyone help me find this. Please guide me.

解决方案

You can use getGenericReturnType which returns a Type rather than a Class, and allows you to get at all the type arguments etc. Short but complete example:

import java.lang.reflect.*;

import java.util.*;

public class Test {

public static void main(String [] args) {

for (Method method : Test.class.getMethods()) {

System.out.println(method.getName());

Type type = method.getGenericReturnType();

System.out.println("Return type: " + type.getTypeName());

if (type instanceof ParameterizedType)

{

ParameterizedType pt = (ParameterizedType) type;

System.out.println("Parameterized: " + pt.getRawType());

for (Type arg : pt.getActualTypeArguments())

{

System.out.println(" " + arg);

}

}

}

}

public static List getNumbers() {

return null;

}

public static List getStrings() {

return null;

}

}

Output includes:

getStrings

Return type: java.util.List

Parameterized: interface java.util.List

class java.lang.String

getNumbers

Return type: java.util.List

Parameterized: interface java.util.List

class java.lang.Integer

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值