/**
* 获得一个类的物理地址
*
* @param cls Class
* @return URL
*/
public static URL getClassLocation(final Class cls) {
if (cls == null)
throw new IllegalArgumentException("null input: cls");
URL result = null;
final String clsAsResource = cls.getName().
replace('.', '/').concat(".class");
final ProtectionDomain pd =
cls.getProtectionDomain();
if (pd != null) {
final CodeSource cs = pd.getCodeSource();
if (cs != null) result = cs.getLocation();
if (result != null) {
if ("file".equals(result.getProtocol())) {
try {
if (result.toExternalForm().
endsWith(".jar") ||
result.toExternalForm().
endsWith(".zip"))
result = new URL("jar:".concat
(result.toExternalForm()).concat
("!/").concat(clsAsResource));
else if (new File(result.
getFile()).isDirectory())
result = new
URL(result, clsAsResource);
} catch (MalformedURLException ignore) {
}
}
}
}
if (result == null) {
final ClassLoader clsLoader = cls.getClassLoader();
result = clsLoader != null ? clsLoader.getResource(clsAsResource) : ClassLoader.getSystemResource(clsAsResource);
}
return result;
}
Java获取一个类的物理地址
最新推荐文章于 2024-07-10 09:46:52 发布