Try making typecast, but get CAP # 1 error

Playing with the casting type for the project, I’m about to start, I unexpectedly found this error:

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

The code that caused this error:

ImyObj testObj = new myObj();
System.out.println(testObj.sayHi());
myObj testObj2 = (testObj.getClass()) testObj;
System.out.println(testObj2.sayBye());

However, this works great:

ImyObj testObj = new myObj();
System.out.println(testObj.sayHi());
myObj testObj2 = (myObj) testObj;
System.out.println(testObj2.sayBye());

Don't they do the same or am I missing something? I currently have Java 1.7_51 installed. It has been a while since I touched Java (before 1.7) since I immersed myself in Python 2.7.

EDIT:

Louis Wassermann's answer also raises the same error.

+3
source share
1 answer

The first problem is that you are trying to use an instance Classas a type. This is not true - it must be a type.

, ( myObj myObj / ):

ImyObj testObj = new MyObj();
MyObj testObj2 testObj.getClass().cast(testObj);

.

testObj.getClass() Class<? extends ImyObj>, "-, ImyObject". ; , .

:

MyObj testObj2 = MyObj.class.cast(testObj);

; . , :

MyObj mo = new MyObj();
MyObj testObj2 mo.getClass().cast(testObj); 

mo.getClass() Class<? extends MyObj>, myObj, myObj, myObj

testObj myObj, java.lang.ClassCastException

+6

All Articles