Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing a Class that extends another Class

Tags:

java

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?

like image 981
ligi Avatar asked Mar 27 '12 11:03

ligi


3 Answers

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.

like image 135
pcalcao Avatar answered Nov 10 '22 18:11

pcalcao


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 
    }
}
like image 2
dldnh Avatar answered Nov 10 '22 17:11

dldnh


Try this for your Foo constructor.

public Foo(Class<? extends Class2Extend> myClass) {...
like image 2
karakuricoder Avatar answered Nov 10 '22 19:11

karakuricoder