簡體   English   中英

Java:使用反射正確檢查了類實例化

[英]Java: properly checked class instantiation using reflection

我正在嘗試使用最簡單的反射形式之一來創建類的實例:

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對象會產生一個警告:

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

我嘗試過使用instanceof check方法:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM