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
}
}
Try this for your Foo constructor.
public Foo(Class<? extends Class2Extend> myClass) {...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With