@Test
public void getClassLocation() throws Exception {
Class cls = DefaultListableBeanFactory.class;
URL rt = null;
final String clsResource = cls.getName().replace(".", "/").concat(".class");
final ProtectionDomain pd = cls.getProtectionDomain();
if (pd != null) {
final CodeSource cs = pd.getCodeSource();
if (cs != null) {
rt = cs.getLocation();
}
if (rt != null) {
if ("file".equals(rt.getProtocol())) {
if (rt.toExternalForm().endsWith(".jar") || rt.toExternalForm().endsWith(".zip")) {
rt = new URL("jar:".concat(rt.toExternalForm()).concat("!/").concat(clsResource));
} else if ((new File(rt.getFile()).isDirectory())) {
rt = new URL(rt, clsResource);
}
}
}
}
if (rt == null) {
final ClassLoader loader = cls.getClassLoader();
rt = loader != null
? loader.getResource(clsResource)
: ClassLoader.getSystemResource(clsResource);
}
System.err.println(rt);
}
本文深入探讨了Java类加载机制及其如何定位类资源的过程,包括保护域、代码来源和资源获取策略。
205

被折叠的 条评论
为什么被折叠?



