1.问题描述
向下转型的应用场景是面向接口编程的时候,经常需要向下转型。但是向上转型的应用场景是什么呢?
我看到网上有的说是为了获取父类的方法,子类也可以访问父类的方法啊,就算是覆盖的方法,也可以通过super.方法()来访问父类的方法啊。
2.代码
代码来源是《深入剖析Tomcat》第二章的代码。
package ex02.pyrmont; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; import java.io.File; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class ServletProcessor1 { public void process(Request request, Response response) { String uri = request.getUri(); String servletName = uri.substring(uri.lastIndexOf("/") + 1); URLClassLoader loader = null; try { // create a URLClassLoader URL[] urls = new URL[1]; URLStreamHandler streamHandler = null; File classPath = new File(Constants.WEB_ROOT); // the forming of repository is taken from the createClassLoader // method in // org.apache.catalina.startup.ClassLoaderFactory String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString(); // the code for forming the URL is taken from the addRepository // method in // org.apache.catalina.loader.StandardClassLoader class. urls[0] = new URL(null, repository, streamHandler); loader = new URLClassLoader(urls); } catch (IOException e) { System.out.println(e.toString()); } Class myClass = null; try { myClass = loader.loadClass(servletName); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); servlet.service((ServletRequest) request, (ServletResponse) response); //注:Request实现了ServletRequest接口,这里为什么要向上转型呢? } catch (Exception e) { System.out.println(e.toString()); } catch (Throwable e) { System.out.println(e.toString()); } } }
这行代码将 Request 和 Response 类型的参数强制转换为 ServletRequest 和 ServletResponse,这不是向上,仍然是向下。强制类型转换与变量本身的类型有关,而与变量所指向的对象的实际类型无关。