简体   繁体   中英

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?

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.

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 
    }
}

试试这个Foo构造函数。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM