public static File locationOf(Class clazz) { String path = clazz.getProtectionDomain().getCodeSource().getLocation().getPath(); path = path.contains("!") ? path.substring(0, path.lastIndexOf('!')) : path; if (!path.isEmpty() && path.charAt(0) == '/') { path = "file:" + path; } try { return getRelativeFile(new File(new URL(path).toURI()), currentDir); } catch (Exception e) { Log.severe("", e); return getRelativeFile(new File(path), currentDir); } }
/** 获取类的class文件位置的URL。这个方法是本类最基础的方法,供其它方法调用。 */ public URL getClassLocationURL(final Class cls) { if (cls == null) { throw new IllegalArgumentException("class that input is null"); } 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; }