protectiondomain 与 url 的区别

ProtectionDomain 介绍

可以查看运行时某个类文件所在jar的位置
和 -verbose 命令相似。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private static String () {
if (underlying.getIdentity().equals(ProjectConstants.WAR)) {
return "/WEB-INF";
}

String envPath = WorkContext.getCurrent().getPath();
if (StringUtils.isEmpty(envPath)) {
try {
URL url = ResourceIOUtils.class.getProtectionDomain().getCodeSource().getLocation();
envPath = URLDecoder.decode(url.getPath(), EncodeConstants.ENCODING_UTF_8);
} catch (UnsupportedEncodingException ignored) {

}
int idx = envPath.indexOf(ProjectConstants.WEBINF_NAME);
if (idx < 0) {
idx = envPath.indexOf("classes");
}
if (idx < 0) {
idx = envPath.indexOf("lib");
}
if (idx > 0) {
envPath = envPath.substring(0, idx + ProjectConstants.WEBINF_NAME.length() + 1);
} else {
envPath = RepositoryUtils.getParent(envPath);
}
}

return envPath;
}

上面这段代码的优点,就是无论什么情况,都能读取到 web-inf 的值。