Java – binding generic parameters to class > Uncheck when
•
Java
I have some code. It uses the class name provided externally. It needs to construct an instance that implements an interface. Let's call it foo
As part of this process, I want to have the following functions:
private static Class<? extends Foo> fooFromClassName(String name) throws ClassNotFoundException { return (Class<? extends Foo>) Class.forName(name); }
This clearly leads to an unchecked warning because it is indeed unsafe - the caller may have requested "Java. Lang. long" for everyone we know I finally like this method to ensure that if it does not throw, the returned class represents a foo implementation
My best solution is:
private static Class<? extends Foo> fooFromClassName(String name) throws ClassNotFoundException { Class<?> impl = Class.forName(name); if (Foo.class.isAssignableFrom(impl)) { @SuppressWarnings("unchecked") Class<? extends Foo> foo = (Class<? extends Foo>) impl; return foo; } else { // Throw something - ClassCastException perhaps. } }
Is there a better way? Is there a way to suppress warnings indefinitely?
Solution
Class. asSubclass:
private static Class<? extends Foo> fooFromClassName(String name) throws ... { return Class.forName(name).asSubclass(Foo.class); }
If the requested class is not a subclass of foo (or foo itself), you will get ClassCastException In other words, it's exactly the same as your solution
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码