Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic type of local variable at runtime

Is there a way in Java to reflect a generic type of a local variable? I know you can do that with a field - Get generic type of java.util.List. Any idea how to solve, for instance:

public void foo(List<String> s){
  //reflect s somehow to get String
}

Or even more general:

public void foo<T>(List<T> s){
  //reflect s somehow to get T
}
like image 468
Bober02 Avatar asked Mar 04 '26 06:03

Bober02


1 Answers

No. Due to Java's Type Erasure, all generics are stripped during the compile process.

You can however use instanceOf or getClass on elements in the list to see if they match a specific type.

like image 149
Johan Sjöberg Avatar answered Mar 06 '26 18:03

Johan Sjöberg