开发者

How to use an object of type class from an generic class as a parameter? - generics and reflection combined

开发者 https://www.devze.com 2023-02-06 06:44 出处:网络
I have two classes: public abstract class MyAbstractSuperClass<A, B> { public MyAbstractSuperClass(Class<A> a, Class<B> b) {

I have two classes:

public abstract class MyAbstractSuperClass<A, B> {

    public MyAbstractSuperClass(Class<A> a, Class<B> b) {
        ...
    }

    ...
}

public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass<A>> {

    public MyClass(Class<A> a) {
    super(a, MyOtherClass.class));
            ...
    }

    ...
}

Now you see, the subclass has to call the superclas开发者_Python百科s's constructor. At that line I get the following error:

The constructor MySuperClass<A, MyOtherClass<A>>(Class<A>, Class<MyOtherClass>) is undefined
  • So how do I get an object of type Class<MyOtherClass<A>>?
  • And how do I do it in the super constructor call, where I can't execute much?

Thanks in advance.


The constructor is expecting a Class<MyOtherClass<A>>, not a Class<MyOtherClass>. The only way I can think to satisfy the compiler is through an ugly series of casts:

@SuppressWarnings("unchecked") 
public MyClass(Class<A> a) {
   super(a, (Class<MyOtherClass<A>>)(Class<?>)MyOtherClass.class);
}

It is type safe as seen through inspection, since the class literal for the raw type MyOtherClass is the same as for the parameterized MyOtherClass<A>. But that doesn't stop an unchecked warning from being generated, which can be suppressed as above, or simply ignored.


Remove the type parameter of MyOtherClass in the MyClass definition. You're apparently not interested in this anywhere in MyClass' body.

public class MyClass<A> extends MyAbstractSuperClass<A, MyOtherClass> {
    public MyClass(Class<A> a) {
       super(a, MyOtherClass.class);
    }
}

Add a @SuppressWarnings("rawtypes") if the warning bothers you.


You must add a second argument to the MyClass constructor:

public MyClass(Class<A> a, Class<MyOtherClass<A>> bClass) {
    super(a, bclass));
}

@Bert F: This does "pass the buck" in some sense, but it passes the buck to someone who can actually provide a class literal of the appropriate type. The caller knows the actual value of the type variable A, and so can provide a class literal of the correct type. Due to erasure, MyClass can't do that.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号