简体   繁体   English

获取参数类型反射

[英]Get Parameter Type Reflection

How would I go about to get the Parameter Type? 我将如何获取参数类型? When I previously attempted to just do classMethods[i].getParameterTypes() my result ended up being Ljava.lang.Class;@4c5bb434 and it repeated with different values for each method. 当我以前尝试只做classMethods[i].getParameterTypes()我的结果最终是Ljava.lang.Class;@4c5bb434并且对于每个方法,它使用不同的值重复进行。

classMethods is an array of Method that obtains all the declaredmethods of the class. classMethods是一个Method数组,它获取该类的所有声明的方法。

Yes, getParameterTypes() returns an array - one element for each parameter. 是的, getParameterTypes()返回一个数组-每个参数一个元素。 Just use: 只需使用:

for (Class<?> clazz : classMethods[i].getParameterTypes()) {
    System.out.println("Parameter type " + clazz.getName());
}

(Adjust the output according to your need, of course.) (当然,可以根据需要调整输出。)

If your parameters type is a generic parameter then this is impossible because generics in Java are only considered at compile time. 如果您的参数类型是泛型参数,那么这是不可能的,因为Java的泛型仅在编译时考虑。 Thus, the Java generics are just some kind of pre-processor. 因此,Java泛型只是某种预处理器。

So here is what I would say. 所以这就是我要说的。 I think you changed the question though :: 我认为您通过::改变了问题:

 for(int i=0; i < classMethods.length;i++) 
    {
     System.out.println(classMethods[i].getName() + " (" + className + ", " 
     + printParameters((Class<String>[])classMethods[i].getParameterTypes()) +  
     ") -> " + classMethods[i].getReturnType());
    }

printParameters prints the method parameters if any : printParameters打印方法参数(如果有):

public static String printParameters(Class<String>[] a)
    {
        String temp="";
        if(a!=null)
        {       

        for(int i=0;i<a.length;i++)
        {
            if(temp!="")
            {
                temp+=", "+a[i].getName();
            }
            else
            {
                temp = a[i].getName();
            }
        }
        }
        return temp;
  }

This should give you the desired result. 这应该给您期望的结果。

Hope this helps... 希望这可以帮助...

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

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