So I'm on vacation right now with no computer. But... Can't stop thinking about code. Totally obsessed. Anyway, cant test this on my own right now, so asking here if this will work:
public <T> void foo(T t){
doSomething(T.class);
}
I know all about type erasure, but never thought about it this way. In this case, T will be an actual object passed to this method so, thanks to the implicit casting that generics use at runtime, would the actual class type of T be passed to doSomething at runtime? Or does the fact that T is essentially just Object with casting ruin that?
No that will not work.
You cannot get the class or getClass() of a generic type at runtime.
In cases where you need to do stuff with the actual class itself, you have to store it and explicitly have to assign it to something like Class<T> genericClass.
public <T> void foo(T t, Class<T> genericClass) { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With