1 Reply Latest reply on Nov 11, 2010 3:56 PM by 103027

    Determine generic types of method parameters

      So I'm using reflection to look at a method. I know the name of the method, and I know that it takes a typed list, but I don't know what type of list it is. How do I get that bit of information?

      e.g. (rather simplified)
      String methodName = "aMethod";
      Class clazz = [whatever]
      Method aMethod = clazz.getMethod(methodName, java.util.List.class);
      This works fine, and calling aMethod.getGenericString() returns something like " void aMethod(java.util.List<java.lang.String>) "

      So I can see in this case that, ahah! it takes a list of Strings.

      But getGernericString is the only method I can find that has this information, and for now, I've resorted to parsing that string to determine the type of list that it takes. This seems to me to be a terrible way to do it.

      Is there a better way?

      On another note, and probably not worth a thread of its own, suppose I know the name of a method that is overloaded, but don't know what the overloading parameter lists are. Currently, I have to go through all the methods and fine the ones that match, e.g.
      for(Method method : clazz.getMethods() ) {
         if(method.getName().equals("aMethod") {
            //do something
      Is there a better way?
        • 1. Re: Determine generic types of method parameters
          Method aMethod = clazz.getMethod("aMethod", java.util.List.class);
          ParameterizedType parmType = (ParameterizedType) aMethod.getGenericParameterTypes()[0];
          Class<?> typeArg = (Class<?>) parmType.getActualTypeArguments()[0];
          Note here that we're assuming the declaration of the List argument to aMethod is an actual Class. It might be a wildcard type, a type variable, etc. In such cases, the downcast to Class<?> will fail. You'd have to type-check the result of getActualTypeArguments()[0] to determine the correct course of action.