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

时间:2011-04-12 15:11:24

标签: 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();

对我们从Class.forName获得的未知类对象进行类型转换会产生警告:

Type safety: Unchecked cast from Class<capture#1-of ?> to Class<? extends My>

我尝试使用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方法。

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

3 个答案:

答案 0 :(得分:5)

您就是这样做的:

/**
 * 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");

答案 1 :(得分:4)

我认为你可以这样做:

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();

答案 2 :(得分:0)

请参阅此问题How do I address unchecked cast warnings?。我发现在反思的地方,你最好只负责任地使用@SuppressWarnings("unchecked")