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?

1
  • 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 Commented Dec 25, 2015 at 0:05

1 Answer 1

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) { ... }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.