Gre*_*Cat 5 java reflection compiler-warnings type-safety
我正在尝试使用最简单的反射形式之一来创建类的实例:
package some.common.prefix;
public interface My {
void configure(...);
void process(...);
}
public class MyExample implements My {
... // proper implementation
}
String myClassName = "MyExample"; // read from an external file in reality
Class<? extends My> myClass =
(Class<? extends My>) Class.forName("some.common.prefix." + myClassName);
My my = myClass.newInstance();
Run Code Online (Sandbox Code Playgroud)
对我们得到的未知类对象进行类型转换会Class.forName产生警告:
Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>
我尝试过使用instanceofcheck方法:
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if (myClass instanceof Class<? extends RST>) {
Class<? extends My> myClass = (Class<? extends My>) loadedClass;
My my = myClass.newInstance();
} else {
throw ... // some awful exception
}
Run Code Online (Sandbox Code Playgroud)
但这会产生编译错误:
Cannot perform instanceof check against parameterized type Class<? extends My>. Use the form Class<?> instead since further generic type information will be erased at runtime.所以我想我不能使用instanceof方法.
我如何摆脱它,我该如何正确地做到这一点?是否可以在没有这些警告的情况下使用反射(即不忽略或压制它们)?
这是你如何做到的:
/**
* Create a new instance of the given class.
*
* @param <T>
* target type
* @param type
* the target type
* @param className
* the class to create an instance of
* @return the new instance
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public static <T> T newInstance(Class<? extends T> type, String className) throws
ClassNotFoundException,
InstantiationException,
IllegalAccessException {
Class<?> clazz = Class.forName(className);
Class<? extends T> targetClass = clazz.asSubclass(type);
T result = targetClass.newInstance();
return result;
}
My my = newInstance(My.class, "some.common.prefix.MyClass");
Run Code Online (Sandbox Code Playgroud)