01: package it.stefanochizzolini.reflex;
02:
03: import java.io.File;
04: import java.net.URI;
05: import java.net.URL;
06:
07: public class Class {
08: /**
09: Retrieves the primary available location of a class.
10:
11: @param className The name of the class whose location has to be retrieved.
12: @return The primary location of the class.
13: */
14: public static String getLocation(String className) {
15: String classResourcePath = className.replace('.', '/')
16: + ".class";
17: // Get class position!
18: URL classUrl = Thread.currentThread().getContextClassLoader()
19: .getResource(classResourcePath);
20: if (classUrl == null)
21: return null;
22:
23: // Get class location!
24: String location;
25: try {
26: location = new File(classUrl.getFile()).getPath();
27: } catch (Exception e) {
28: throw new RuntimeException(e);
29: }
30:
31: try {
32: location = java.net.URLDecoder.decode(location, "UTF-8");
33: } catch (Exception e) {/* NOOP. */
34: }
35:
36: // Is it inside a jar file?
37: int index = location.indexOf("!");
38: if (index >= 0) {
39: // Eliminate the inner path!
40: location = location.substring(0, index);
41: }
42: // Is there a protocol identifier?
43: index = location.indexOf(":");
44: if (index >= 0) {
45: // Eliminate the leading protocol identifier!
46: location = location.substring(++index);
47: }
48:
49: return location;
50: }
51: }
|