I'm looking at this example from a Spring Boot guide:
@Component
public class SimpleCORSFilter implements Filter {
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
chain.doFilter(req, res);
}
public void init(FilterConfig filterConfig) {}
public void destroy() {}
And am confused by this line:
HttpServletResponse response = (HttpServletResponse) res;
I understand the cast from ServletResponse
to HttpServletResponse
is necessary because the latter interface has #setHeader()
. But why does this cast work? Does it work because the underlying object passed to the method is a HttpServletResponse
?
But runtime aside, why does the compiler allow this? I'm new to Java and would have expected this cast to fail, since it's from a less to more specific type. For example, using Element and Vertex, I've had this fail:
Vertex v = (Vertex) e; // `e` is an `Element`