简体   繁体   中英

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 is an array of Method that obtains all the declaredmethods of the class.

Yes, getParameterTypes() returns an array - one element for each parameter. 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. Thus, the Java generics are just some kind of pre-processor.

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 :

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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