Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: generic method with .class on generic parameter [duplicate]

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?

like image 919
craigmiller160 Avatar asked Aug 11 '26 04:08

craigmiller160


1 Answers

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) { ... }
like image 71
luk2302 Avatar answered Aug 14 '26 05:08

luk2302