I'm mocking some code for testing. In one mock, I'm trying to mock ServletFileUpload::parseRequest
, which returns a List of FileItems.
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
private class MockServletFileUpload extends ServletFileUpload {
List<MockDiskFileItem> fileItems;
@Override
public List<FileItem> parseRequest(HttpServletRequest request) {
return fileItems;
}
}
but Eclipse signals an error on the method's return: Type mismatch: cannot convert from List<MockDiskFileItem> to List<FileItem>
. But MockDiskFileItem implements FileItem
! Why doesn't this work?
On the other hand, this version of the method, which casts the individual elements of the List to the parent class, doesn't give errors:
@Override
public List<FileItem> parseRequest(HttpServletRequest request) {
return fileItems.stream()
.map( dfi -> (FileItem) dfi )
.collect(Collectors.toList());
}
Why do the elements have to be individually cast? And is there any shorter way to write this?
UPDATE
To clarify, my question is primarily a practical one: how to convert/cast from List<MockDiskFileItem>
to List<FileItem>
most efficiently. I'd also like to know why Java can't automatically do the conversion/cast of the whole list, when as should be clear to anyone who takes the time to read the second version of the method, Java will automatically convert/cast any MockDiskFileItem
to FileItem
.
UPDATE 2
I actually have an answer to my own question that shows why this question is different and not a duplicate. And you can see from the one answer below how this is a different question. Why was this closed? You moderators are too heavy handed. How many reputation points did that gain you? And what did it cost this site's integrity?