Guest User

Untitled

a guest
Feb 20th, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.98 KB | None | 0 0
  1. import java.io.File;
  2. import java.net.MalformedURLException;
  3. import java.net.URL;
  4. import java.security.CodeSource;
  5. import java.security.ProtectionDomain;
  6.  
  7. /**
  8. * Creted on 2018/2/8.
  9. */
  10. public class TestGetClassFromWhichJarLocation {
  11.  
  12. public static void main(String[] args) {
  13. try {
  14. Class<?> cls = Class.forName("java.lang.String");
  15. URL classLocation = getClassLocation(cls);
  16. System.out.println(classLocation);
  17. } catch (ClassNotFoundException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21.  
  22. public static URL getClassLocation(final Class cls) {
  23. if (cls == null) {
  24. throw new IllegalArgumentException("null input: cls");
  25. }
  26. URL result = null;
  27. final String clsAsResource = cls.getName().replace('.', '/').concat(".class");
  28. final ProtectionDomain pd = cls.getProtectionDomain();
  29. if (pd != null) {
  30. final CodeSource cs = pd.getCodeSource();
  31. if (cs != null) result = cs.getLocation();
  32. if (result != null) {
  33. if ("file".equals(result.getProtocol())) {
  34. try {
  35. if (result.toExternalForm().endsWith(".jar") || result.toExternalForm().endsWith(".zip"))
  36. result = new URL("jar:".concat(result.toExternalForm()).concat("!/").concat(clsAsResource));
  37. else if (new File(result.getFile()).isDirectory()) {
  38. result = new URL(result, clsAsResource);
  39. }
  40. } catch (MalformedURLException ignore) {
  41. ignore.printStackTrace();
  42. }
  43. }
  44. }
  45. }
  46. if (result == null) {
  47. final ClassLoader clsLoader = cls.getClassLoader();
  48. result = clsLoader != null ?
  49. clsLoader.getResource(clsAsResource) :
  50. ClassLoader.getSystemResource(clsAsResource);
  51. }
  52. return result;
  53. }
  54.  
  55. }
Add Comment
Please, Sign In to add comment