Passing a class that extends another class

I boiled the thing I want to do, down to the following minimal code:

public class TestClass {

    class Class2Extend {
    }

    class Foo {
        public Foo(Class<Class2Extend> myClass) {

        }
    }

    class Bar extends Class2Extend{

    }

    public TestClass() {
        new Foo(Class2Extend.class); // works fine 
            //new Foo(Bar.class); -> fails even though Bar extends Class2Extend - but I want something like this to have nice code
    }
}

      

I can use the interface, but it would be cleaner. Can anyone give me a hint / trick on this issue?

+3


source to share


3 answers


Change to:

class Foo {
    public Foo(Class<? extends Class2Extend> myClass) {

    }
}

      



When you say that your argument is of a type Class<Class2Extend>

, Java matches exactly that type of parameters, and not to any subtypes, you must explicitly state that you want some class to extend Class2Extend.

+12


source


you can call it however you want if you change the constructor Foo

to allow subclasses:



public class TestClass {

    class Class2Extend {
    }

    class Foo {
        public Foo(Class<? extends Class2Extend> myClass) {

        }
    }

    class Bar extends Class2Extend{

    }

    public TestClass() {
        new Foo(Bar.class); // works fine 
    }
}

      

+1


source


Try this for your Foo constructor.

public Foo(Class<? extends Class2Extend> myClass) {...

      

+1


source







All Articles