简体   繁体   English

使用Java反射,如何获取方法的参数化参数类型?

[英]Using Java reflection, how do I get parameterized types of parameters to a Method?

Let's say I have a Method: 假设我有一个方法:

public void method(LinkedList<Integer> intList);

I use reflection to obtain the java.lang.reflect.Method for this method, and I want to obtain the ParameterizedType, ie. 我使用反射来获取此方法的java.lang.reflect.Method,并且我想获取ParameterizedType,即。 LinkedList<Integer>. LinkedList <整数>。

Unfortunately, using Method.getParameterTypes() I can only seem to get the non-parameterized Class Class<LinkedList>. 不幸的是,使用Method.getParameterTypes()我似乎只能得到非参数化的类Class <LinkedList>。

However in my debugger if I look at the Method object I san see that there is a "signature" field that does appear to contain the generic information: 但是,在调试器中,如果我查看Method对象,我会发现有一个“签名”字段,该字段似乎包含通用信息:

(Ljava/util/LinkedList<Ljava/lang/Integer;>;)V

So how can I obtain the LinkedList parameterized type from the Method object? 那么如何从Method对象获取LinkedList参数化类型?

Use Method.getGenericParameterTypes . 使用Method.getGenericParameterTypes Sample code: 样例代码:

import java.lang.reflect.*;
import java.util.*;

public class Test {

    public void foo(LinkedList<Integer> intList) {
    }

    public static void main(String[] args) throws Exception {
        Method method = Test.class.getMethod("foo", LinkedList.class);
        Type[] parameters = method.getGenericParameterTypes();
        System.out.println(parameters[0]);
    }
}

Output: 输出:

java.util.LinkedList<java.lang.Integer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM