0

In a regular method I can get parameter class like this:

public void methodA(String param)
{
    Class typeA = String.class;
    // or
    Class typeB = param.getClass();
} 

In a generic method this still works:

public <T> void methodB(T param)
{
    Class type = param.getClass();
} 

But what about this:

public <T> void methodC(ArrayList<T> param)
{    
    //Class type = ??? 
    //How to get T class?
    //Something like "Class type = T" would be nice
}
AppleMoose
  • 123
  • 1
  • 1
  • 9
  • Is [this](https://stackoverflow.com/questions/3437897/how-do-i-get-a-class-instance-of-generic-type-t?rq=1) solves your problem? – ThilankaD Jun 23 '21 at 17:27
  • 1
    The sanest solution is to get out `param.get(0).getClass()` to do something equivalent to your `methodB`. That isn't _actually_ sane, it's just the best you can hope for. – Louis Wasserman Jun 23 '21 at 17:29
  • Why do you need the `Class` object? Usually in generic methods where the `Class` object is required, it's added as a parameter to the method, typed as `Class`. – rgettman Jun 23 '21 at 17:35
  • Thanks. So it looks like there is no "easy" way. I suppose I will send it as an extra parameter then. (That is also my current workaround, but I thought perhaps there was a simple solution to avoid the extra parameter.) – AppleMoose Jun 23 '21 at 18:49

0 Answers0