My code is as follows
package com.foo;
public class TestComposition {
public static void main(String[] args) {
try {
Class<Foo> fooClass =
(Class<Foo>) Class.forName("Foo");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
The assignment within the 'try' block results in a warning stating
Type safety: Unchecked cast from Class<capture#1-of ?> to
Class<Foo>
Why is this?
Firstly, if you know the exact class then you don't need Class.forName
. Foo.class
will do. (Prior to J2SE 5.0, Foo.class
actually compiled to doing Class.forName("Foo")
and then caching it in a static.)
What you probably want is something like:
Class<? extends Foo> fooClass =
(Class<? extends Foo>) Class.forName("MyFoo");
(When I say want, casts and particularly reflection are evil.)
As it happens, you there is an appropriate method to do the cast "safely" (assuming Foo
is not itself generic). Safely as in not providing a reference to an incompatible object, not as in there are no bug or no unexpected exception.
Class<? extends Foo> fooClass =
Class.forName("MyFoo").asSubclass(Foo.class);
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