a我考网

 找回密码
 立即注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

查看: 91|回复: 0

[其他] JAVA技巧:如何寻找一个类X实例中类的物理所在?

[复制链接]
发表于 2012-8-4 12:28:23 | 显示全部楼层 |阅读模式
在我给你谜底之前,我必需指出,如不美观你坚持养成一个好习惯--编轨范时老是考虑与硬盘位置无关,那么你的java进修将会进展的很顺遂.当你要装载资本的时辰,好比一些属性和设置装备摆设文件,尽可能的使用ResourceBundle.getBundle()而不是使用java.util.File,除非真的是必需这样.这样做不仅有利于你的J2EE应用开发,而且越到后来,你就越会发现,我怎媚暌剐那么多工具要装载?这个时辰,你就会感受这个体例确实给你带来了便利.尽管如斯,追寻到class的根阅暌剐时辰在轨范测试和debug的时辰会很有用,因为这个设法,我给出了一种很有辅佐的体例能够替我们完成这个使命,这些所有都是基于j2se的api的.
% H0 O- e2 a  E7 V- [1 [" ^3 w. H  /**
3 e7 V: v* U5 P# F5 b  * Given a Class object, attempts to find its .class location [returns null! H" g$ u- E9 n) v4 n6 f6 S: a8 G
  * if no such definition can be found]. Use for testing/debugging only.
; E/ Q4 x0 |4 g( M/ F+ k  *' s5 z7 n( S) u* M% H. G- n3 i) X
  * @return URL that points to the class definition [null if not found].* T# ~' e4 |* J* l
  */- I# ]: F- V$ p
  public static URL getClassLocation (final Class cls)
) D! t; Y1 I" a0 o* k4 P! H  {/ J! o+ X; U. Q5 _: ?/ W; T
  if (cls == null) throw new IllegalArgumentException ("null input: cls");URL result = null;" e: q) l( L3 k* @5 H) X5 A( G  X! A5 R
  final String clsAsResource = cls.getName ().replace (‘.‘, ‘/‘).concat (".class");final ProtectionDomain pd = cls.getProtectionDomain ();( w- M4 h5 [4 M7 S' w/ Y
  // java.lang.Class contract does not specify if ‘pd‘ can ever be null;
8 ]: s7 T9 x# [5 {. ^  // it is not the case for Sun‘s implementations, but guard against null% P: r' r0 \1 |6 e0 I$ U+ Q4 N
  // just in case:# e* Y3 X! L' M: ^9 w* E9 {
  if (pd != null)- A, J! H* k/ M1 h1 O2 A
  {
+ ^$ f+ G# i' j8 h6 o3 O) n- m  final CodeSource cs = pd.getCodeSource ();
0 F* P* [; p* d/ Z( |; c5 L/ |8 N/ _  // ‘cs‘ can be null depending on the classloader behavior:
+ Y4 f" d4 D# _7 b, q/ l3 U  if (cs != null) result = cs.getLocation ();if (result != null)
5 F* X8 k3 ~/ D7 r0 `. z7 B  {5 V& r2 A- O& F4 j" P, `, }
  // Convert a code source location into a full class file location
4 P9 w- p6 E( B* A  // for some common cases:* E" }+ O2 O2 l# U9 r6 |
  if ("file".equals (result.getProtocol ()))
0 L2 V& y7 q4 e8 I0 a  {6 B3 l( R# R% I
  try6 y+ V5 }# Q$ {6 Y9 r, @- ~
  {
" x, q5 \- k1 N& f; W' {  if (result.toExternalForm ().endsWith (".jar")
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|Woexam.Com ( 湘ICP备18023104号 )

GMT+8, 2024-6-17 01:07 , Processed in 0.259714 second(s), 21 queries .

Powered by Discuz! X3.4 Licensed

© 2001-2017 Comsenz Inc.

快速回复 返回顶部 返回列表