How to reverse wildcard (?) To generic type T?

I have a static method that I want to use to load classes and instantiate my objects at runtime, but when I compile, I got this warning:

warning: [unchecked] unchecked cast
            T t = (T) ctor.newInstance();
required: T
found:    CAP#1
where T is a type-variable:
    T extends Object declared in method <T>forName(String,Set<String>)
    where CAP#1 is a fresh type-variable:
    CAP#1 extends Object from capture of ?
1 warning

Here is the code:

public static <T> Set<T> forName(String modulePath, Set<String> classes) throws InvalidModuleException{
    try {
        ClassLoader cl = new URLClassLoader(new URL[]{new URL(modulePath)});

        Set<T> list = new HashSet<>(classes.size());
        for (String className : classes) {
            Class<?> clazz = (Class<?>) Class.forName(className, true, cl);
            Constructor<?> ctor = clazz.getConstructor();
            T t = (T) ctor.newInstance();
            list.add(t);
        }
        return list;    
    } catch (MalformedURLException | ReflectiveOperationException ex) {
        throw new InvalidModuleException(ex.getMessage());
    }
}

Can anyone explain this to me?

[UPDATE] Here is an example of a method call:

HashSet<String> set = new HashSet<>();
h.add("fully_classfied_classname_readed_from_file"); //Class that extends AbstractApplication
Set<AbstractApplication> abs = Apps.forName("plugins/module.jar", set);
+4
source share
2 answers

There is one missing bit. First, you are trying to give meaning to each object T. If you know Tprehand, I see no reason why you need to pass a set of strings when the class object will do

Suppose you still need to, if possible, subclasses:

public static <T> Set<? extends T> forName(String modulePath, Set<String> classes, Class<T> claz) throws InvalidModuleException{
    try {
    ClassLoader cl = new URLClassLoader(new URL[]{new URL(modulePath)});

    Set<T> list = new HashSet<>(classes.size());
    for (String className : classes) {
        Class<?> clazz = Class.forName(className, true, cl);
        Constructor<?> ctor = clazz.getConstructor();
        Object obj = ctor.newInstance();
        list.add(claz.cast(obj));
    }
    return list;
} catch (MalformedURLException | ReflectiveOperationException | ClassCastException ex) {
    throw new InvalidModuleException(ex.getMessage());
}
}
+1

, . -, , ; , , , , T.

, , , T:

Set<Class<? extends T>> classes

:

for (Class<? extends T> clazz : classes) {
  Constructor<? extends T> ctor = clazz.getConstructor();
  T t = ctor.newInstance();
  list.add(t);
}

, , @SuppressWarnings , , , .

+3

Source: https://habr.com/ru/post/1624098/


All Articles