ligi
ligi

Reputation: 39519

passing a Class that extends another Class

I boiled the thing I want to do 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 an interface but it would be cleaner this way. Anyone can give me a hint/trick on this problem?

Upvotes: 8

Views: 7526

Answers (3)

karakuricoder
karakuricoder

Reputation: 1075

Try this for your Foo constructor.

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

Upvotes: 2

dldnh
dldnh

Reputation: 8951

you can call it the way you wanted to if you change the Foo constructor 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 
    }
}

Upvotes: 2

pcalcao
pcalcao

Reputation: 15965

Change to:

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

    }
}

When you say your argument is of type Class<Class2Extend> Java matches exactly to that parameter type, not to any sub-types, you have to explicitly specify that you want any class that extends Class2Extend.

Upvotes: 14

Related Questions