3

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?

Tarik
  • 4,961
  • 3
  • 36
  • 67
craigmiller160
  • 5,751
  • 9
  • 41
  • 75
  • This is not a duplicate question, the OP is asking why this is not working and he is providing a different example. Also he is not asking for a workaround like the other question! I don't have reopen privelege, but this must not be marked as duplicate – Tarik Dec 25 '15 at 00:05

1 Answers1

3

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) { ... }
luk2302
  • 55,258
  • 23
  • 97
  • 137