This first is an ordinary cast. It requires that the type to cast to is known at compile time. It verifies at compile time that the cast can be correct, and checks (if the type to cast to is not generic) that the cast is correct at runtime.
The second uses the reflection api. It requires that the class to cast to is known at runtime. It doesn't verify anything at compile time, but always checks that the cast is correct at runtime.
Type parameters are only known at compile type, hence you can not use the second approach for a type parameter (the expression T.class
does not compile).
Dynamically loaded classes (for instance with Class.forName(String)) are only known at runtime, hence the first approach can not be used.
Edit: However, as Pavel points out, it makes no sense to cast to a dynamically loaded class. I agree that the only real usefulness of Class.cast(Object)
is to cast to a type parameter for which you happen to have a class object available.
If the type to cast to does not contain a type parameter, the first approach is better, as the additional compile time checking can catch bugs, you lose no type safety at runtime, and get a shorter syntax to boot.