我正试图使用一种最简单的反射形式来创建类的实例:
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();
我们从Class.forName
得到的类型转换未知Class对象会产生警告:
类型安全:未选中从类强制转换<捕获第1个>到类<?扩展我的>
我尝试过使用instanceof
检查方法:
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
}
但这会产生编译错误: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");
我认为你可以这样做:
Class<? extends My> myClass= null;
Class<?> loadedClass = Class.forName("some.common.prefix." + myClassName);
if(My.class.isAssignableFrom(loadedClass))
{
myClass = loadedClass.asSubclass(My.class);
}
My my = myClass.newInstance();
请参阅此问题如何解决未检查的强制转换警告?。我发现,在涉及反射的情况下,您最好负责任地使用@SuppressWarnings("unchecked")