Question

I want method public void x(List<Class<some expression>> m) to throw an error if you try to pass a class which does not extend class A{} by replacing "some expression" with... some expression.

I always get an annoying warning when I use a wildcard or don't include it, so I would like to understand why Class deserves a dimension at all, even if I'm totally off base as to how it's used.

Was it helpful?

Solution

I don't exactly get what you want to do. Actually, this method signature:

public void x(List<? extends YourClass> m)

will not compile if you pass a List of objects whose class doesn't extend YourClass (let's call it so, instead of A).

If you want your x method to get, as a parameter, a list of Class objects, that's another issue. Are you sure you are not willing to just pass a List of objects of a class that extends YourClass? If so, that method signature should work.

EDIT: Since you stated you want to pass a list of classes, then this should work:

public void x(List<Class<? extends YourClass>> m)

Tested this way:

import java.util.*;

class YourClass {}
class YourClassEx extends YourClass {}

public class Test {

    public static void x(List<Class<? extends YourClass>> m) {
        // stuff...
    }

    public static void main(String[] argv) {

        List<Class<? extends YourClass>> list = new ArrayList<>();
        list.add(YourClass.class);
        list.add(YourClassEx.class);
        x(list); // compiles fine until here

        list.add(String.class); // doesn't compile
        x(new ArrayList<Class>()); // doesn't compile, either

    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top