Java:使用反射正确检查类实例化 [英] Java: properly checked class instantiation using reflection

查看:91
本文介绍了Java:使用反射正确检查类实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用一种最简单的反射形式来创建类的实例:

I'm trying to use one of the simplest forms of reflection to create an instance of class:

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 会产生警告:

Typecasting unknown Class object we've got from Class.forName yields a warning:

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
}

但这会产生编译错误:
无法对参数化类型Class< ;?执行instanceof检查吗?扩展My>。请使用Class<?>形式相反,因为进一步的泛型类型信息将在运行时删除。所以我想我不能使用 instanceof 方法。

but this yields a compilation error: 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. So I guess I can't use instanceof approach.

我如何摆脱它,我应该如何正确地做到这一点?

How do I get rid of it and how am I supposed to do it properly? Is it possible to use reflection without these warnings at all (i.e. without ignoring or supressing them)?

推荐答案

这是怎么做的?它:

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

这篇关于Java:使用反射正确检查类实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆