Created
February 8, 2018 08:52
-
-
Save zhanggang807/991612d7e4a00a6271da35dc1116f58a to your computer and use it in GitHub Desktop.
print a class in which jar file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.File; | |
import java.net.MalformedURLException; | |
import java.net.URL; | |
import java.security.CodeSource; | |
import java.security.ProtectionDomain; | |
/** | |
* Creted on 2018/2/8. | |
*/ | |
public class TestGetClassFromWhichJarLocation { | |
public static void main(String[] args) { | |
try { | |
Class<?> cls = Class.forName("java.lang.String"); | |
URL classLocation = getClassLocation(cls); | |
System.out.println(classLocation); | |
} catch (ClassNotFoundException e) { | |
e.printStackTrace(); | |
} | |
} | |
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) { | |
ignore.printStackTrace(); | |
} | |
} | |
} | |
} | |
if (result == null) { | |
final ClassLoader clsLoader = cls.getClassLoader(); | |
result = clsLoader != null ? | |
clsLoader.getResource(clsAsResource) : | |
ClassLoader.getSystemResource(clsAsResource); | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment