避免在Java中使用多个If语句

我已经编写了类似这样的方法。但是我猜这应该进行重构。谁能建议最好的方法来避免使用多个if语句?

private String getMimeType(String fileName){

if(fileName == null) {

return "";

}

if(fileName.endsWith(".pdf")) {

return "application/pdf";

}

if(fileName.endsWith(".doc")) {

return "application/msword";

}

if(fileName.endsWith(".xls")) {

return "application/vnd.ms-excel";

}

if(fileName.endsWith(".xlw")) {

return "application/vnd.ms-excel";

}

if(fileName.endsWith(".ppt")) {

return "application/vnd.ms-powerpoint";

}

if(fileName.endsWith(".mdb")) {

return "application/x-msaccess";

}

if(fileName.endsWith(".rtf")) {

return "application/rtf";

}

if(fileName.endsWith(".txt")) {

return "txt/plain";

}

if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {

return "txt/html";

}

return "txt/plain";

}

我在这里不能使用大小写转换,因为我的“条件”是java.lang.String

回答:

您可以使用Map来保存您的解决方案:

Map<String,String> extensionToMimeType = new HashMap<String,String>();

extensionToMimeType.put("pdf", "application/pdf");

extensionToMimeType.put("doc", "application/msword");

// and the rest

int lastDot = fileName.lastIndexOf(".");

String mimeType;

if (lastDot == -1) {

mimeType = NO_EXTENSION_MIME_TYPE;

} else {

String extension = fileName.substring(lastDot+1);

mimeType = extensionToMimeType.getOrDefault(extension,

UNKNOWN_EXTENSION_MIME_TYPE);

}

为了使此代码起作用,您需要像在类中那样进行定义NO_EXTENSION_MIME_TYPE和定义UNKNOWN_EXTENSION_MIME_TYPE,如下所示:

private static final String NO_EXTENSION_MIME_TYPE = "application/octet-stream";

private static final String UNKNOWN_EXTENSION_MIME_TYPE = "text/plain";

以上是 避免在Java中使用多个If语句 的全部内容, 来源链接: utcz.com/qa/411909.html

回到顶部