1

Forgive me for asking such a question but I have been doing C# for the past couple years until very recently so I am a little rusty on type erasure generics in Java compared to the intuitive version of generics in C#.

I have a situation like so:

public void doSomething(Class<T> classType) {
  for (Method method : classType.getMethods()) {
    for (Class<?> parameterClass : method.getParameterTypes()) {
      // How do I compare parameterClass to classType or to String.class?
    }
  }
}

Since parameterClass is of type Class then it is an unknown class type thus it can't be determined at runtime? Does their exist a way to perform this comparison? Again I aplogize I haven't used Java generics in years and I have been reading up on it and am still confused.

maple_shaft
  • 10,435
  • 6
  • 46
  • 74

1 Answers1

1

Try using method.getGenericParameterTypes() instead of the non-generic getParameterTypes()

Jason S
  • 184,598
  • 164
  • 608
  • 970
  • oh, wait -- you just need to compare types; `getGenericParameterTypes()` is when you actually want to determine the type parameter, assuming it's available. – Jason S May 26 '11 at 12:40
  • This returns an array of Type, which Class implements. Why is this a better idea? – maple_shaft May 26 '11 at 12:42
  • This is where I am confused, how can you COMPARE Types yet not be able to determine the Type parameter? – maple_shaft May 26 '11 at 12:43
  • 1
    @maple_shaft: either you can compare types or you cannot. It depends on what erasure erases. I asked this SO question: http://stackoverflow.com/questions/6021179/java-reflection-how-do-the-method-getgenericxxxxx-methods-work – Jason S May 26 '11 at 13:14
  • Brilliant! This is why `.equals` for generic Class objects seems to work, because the types were concrete when they were compiled. If this didn't occur then generics would be useless. Thanks! – maple_shaft May 26 '11 at 13:20