需要java unchecked强制转换:类<a> found: Class<cap#1> where CAP#1 is a fresh type-variable

时间:2015-07-18 04:04:35

标签: java casting

I am trying to get rid of all my compiler warnings in my code, and this one is a little frustrating.

I need to do some functional operations with the Class object of a particular class that I've created. Let's illustrate with this code:

public static void main(String[] args) {
    A obj = getObj();
    Class<A> clazz = obj.getClass();
}

static class A {}

static A getObj() {
    return new A();
}

This code throws a compiler error:

incompatible types: Class<CAP#1> cannot be converted to Class<A>
  where CAP#1 is a fresh type-variable:
    CAP#1 extends A from capture of ? extends A

Ok, so I cast the obj from getClass():

Class<A> clazz = (Class<A>)obj.getClass();

And I get this warning (better than an error):

[unchecked] unchecked cast
  required: Class<A>
  found:    Class<CAP#1>
  where CAP#1 is a fresh type-variable:
    CAP#1 extends A from capture of ? extends A

So, how do you check the class cast?

Tried this:

Class c = obj.getClass();
Class<A> clazz = c instanceof Class<A> ? (Class<A>)c : null;

But that produced a warning AND an error.

So now I'm stumped.

0 个答案:

没有答案