在Java中,我想做这样的事情:
try {
...
} catch (/* code to catch IllegalArgumentException, SecurityException,
IllegalAccessException, and NoSuchFieldException at the same time */) {
someCode();
}
Run Code Online (Sandbox Code Playgroud)
...代替:
try {
...
} catch (IllegalArgumentException e) {
someCode();
} catch (SecurityException e) {
someCode();
} catch (IllegalAccessException e) {
someCode();
} catch (NoSuchFieldException e) {
someCode();
}
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
我需要将以下内容更改if为switch- case同时检查a String,以提高圈复杂度.
String value = some methodx;
if ("apple".equals(value)) {
method1;
}
if ("carrot".equals(value)) {
method2;
}
if ("mango".equals(value)) {
method3;
}
if ("orange".equals(value)) {
method4;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定我会得到什么价值.
我正在寻找Java7的新功能.我发现一个是 try-with-resources Statement.任何人都可以告诉我它究竟意味着什么?我们应该使用它的原因和位置,以及我们可以利用此功能的地方?即使是try声明也没有catch阻止让我感到困惑.
为什么在没有Catch或Finally的情况下编写Try,如下例所示?
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet tryse</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet tryse at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
Run Code Online (Sandbox Code Playgroud) List<String> list = new ArrayList(); 将导致编译器警告.
但是,以下示例编译时没有任何警告: List<String> list = new ArrayList<>();
我很好奇为什么需要引入钻石操作员.为什么不只是对构造类型推断,如果类型参数是不存在(因为它已经在Java静态方法做,像谷歌番石榴集合库开发)
编辑:使用millimoose答案作为起点我查看了实际上是什么类型的擦除,它不只是删除所有类型信息.编译器实际上做了一些(从官方文档复制):