-3

Is it possible to get the number of type parameters a class has/accepts in Java using its instance? For example,

Map<String, Integer> s = new HashMap<>();
int numParams = getNumOfTypeParameters(s); // Should return 2

I know that due to type erasure we can't get the type of these parameters but can we also not get the number of parameters?

ayushgp
  • 4,891
  • 8
  • 40
  • 75
  • 1
    Did you look through the methods in `java.lang.Class`? It's not hard to find. – Jim Garrison Feb 23 '18 at 07:49
  • ... `Map` always takes 2 parameters. What are you thinking? – user202729 Feb 23 '18 at 07:49
  • @user202729 Yes I know that but I need this method for *any* generic class' instance. – ayushgp Feb 23 '18 at 07:50
  • ---[Actually you can](https://stackoverflow.com/questions/1901164/get-type-of-a-generic-parameter-in-java-with-reflection).--- No you can't, see JonSkeet's comment. – user202729 Feb 23 '18 at 07:53
  • 1
    You know that you are supposed to do *serious* research prior posting questions? – GhostCat Feb 23 '18 at 07:56
  • 1
    Is this question too trivial to post on SO? We have many beginner questions, and this one (as far as I can see) have not been asked on SO. – user202729 Feb 23 '18 at 08:05
  • Why are people so eager to close a question that has not been asked earlier and is quite easy to be overlooked by beginners looking through the docs? This is not duplicate, spam, not about programming or anything that needs to be voted closed. SO is sometimes too intimidating to be asking simple questions even when they've not been asked yet. – ayushgp Feb 23 '18 at 08:14

1 Answers1

1

It's as simple as

System.out.println(Map.class.getTypeParameters().length); // 2

System.out.println(Class.class.getTypeParameters().length); // 1

System.out.println(Object.class.getTypeParameters().length); // 0

Just look at the documentation for java.lang.Class and you'l find this.

Sweeper
  • 213,210
  • 22
  • 193
  • 313