Java:使用reflection正确检查了类实例化

我正在尝试使用最简单的reflectionforms之一来创建类的实例:

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 myClass = (Class) Class.forName("some.common.prefix." + myClassName); My my = myClass.newInstance(); 

我们从Class.forName获取未知的Class对象会产生一个警告:

 类型安全:从Class 到Class  

我尝试过使用instanceof check方法:

 Class loadedClass = Class.forName("some.common.prefix." + myClassName); if (myClass instanceof Class) { Class myClass = (Class) loadedClass; My my = myClass.newInstance(); } else { throw ... // some awful exception } 

但这会产生编译错误: Cannot perform instanceof check against parameterized type Class. Use the form Class instead since further generic type information will be erased at runtime. Cannot perform instanceof check against parameterized type Class. Use the form Class instead since further generic type information will be erased at runtime. 所以我想我不能使用instanceof方法。

我如何摆脱它,我该如何正确地做到这一点? 是否可以在没有这些警告的情况下使用reflection(即不忽略或压制它们)?

这是你如何做到的:

 /** * Create a new instance of the given class. * * @param  * 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 newInstance(Class type, String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = Class.forName(className); Class targetClass = clazz.asSubclass(type); T result = targetClass.newInstance(); return result; } My my = newInstance(My.class, "some.common.prefix.MyClass"); 

我想你可以这样做:

 Class 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")