gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:44 25 4
gpt4 key购买 nike

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

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>

I've tried using instanceof check approach:

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

关于Java:使用反射正确检查类实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com