在我给你谜底之前,我必需指出,如不美观你坚持养成一个好习惯--编轨范时老是考虑与硬盘位置无关,那么你的java进修将会进展的很顺遂.当你要装载资本的时辰,好比一些属性和设置装备摆设文件,尽可能的使用ResourceBundle.getBundle()而不是使用java.util.File,除非真的是必需这样.这样做不仅有利于你的J2EE应用开发,而且越到后来,你就越会发现,我怎媚暌剐那么多工具要装载?这个时辰,你就会感受这个体例确实给你带来了便利.尽管如斯,追寻到class的根阅暌剐时辰在轨范测试和debug的时辰会很有用,因为这个设法,我给出了一种很有辅佐的体例能够替我们完成这个使命,这些所有都是基于j2se的api的.
2 y! f2 Y+ P, @0 V. U+ l /**
. k8 o$ }' e/ _6 M( d * Given a Class object, attempts to find its .class location [returns null
6 ?3 C& d/ Z1 i% R3 y( f' i * if no such definition can be found]. Use for testing/debugging only.
3 G/ d" h: ~* N. u+ l# t6 ` *! c: [. f F% E+ T
* @return URL that points to the class definition [null if not found].9 t1 x7 `2 m5 W
*/ M- O! D5 |0 t
public static URL getClassLocation (final Class cls)
; x" H5 O; R p' l1 F+ _: Z- p7 [ {
/ E" E: h5 |% _ if (cls == null) throw new IllegalArgumentException ("null input: cls");URL result = null;
1 V4 h" G s8 U& a7 Z5 \ final String clsAsResource = cls.getName ().replace (‘.‘, ‘/‘).concat (".class");final ProtectionDomain pd = cls.getProtectionDomain ();. }# \3 S" Y0 Q% d2 `7 |
// java.lang.Class contract does not specify if ‘pd‘ can ever be null;9 U4 s; _% }& ~! D
// it is not the case for Sun‘s implementations, but guard against null- ]* g, C( ^& I6 A, Z# l9 Y! ^
// just in case:/ s" W- t5 f# A
if (pd != null)
. V1 `7 ^8 q4 k! Q* X. d1 t {
8 K. c% l* d* c# [7 h9 H4 d8 x9 x final CodeSource cs = pd.getCodeSource ();2 A6 n6 x1 [2 @ @2 @, L" f% B3 |
// ‘cs‘ can be null depending on the classloader behavior:
3 b8 [% [& j1 C" y$ r5 U if (cs != null) result = cs.getLocation ();if (result != null)
2 `& B+ f! X$ q# `. E {
5 H" r' x% z1 G4 z // Convert a code source location into a full class file location
, q; b" q. v/ w N/ j5 x // for some common cases:
. r7 B8 E6 a, m% A. p if ("file".equals (result.getProtocol ()))
: x4 V. j8 b9 L/ `5 R; B {
; a* [' H5 @: k2 E2 i7 ~+ p+ q: N% `2 k try& }7 F# v0 F- Z4 F. X% j/ W* p
{9 Q5 W g6 S8 E. v
if (result.toExternalForm ().endsWith (".jar") |