会计考友 发表于 2012-8-4 12:28:23

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

在我给你谜底之前,我必需指出,如不美观你坚持养成一个好习惯--编轨范时老是考虑与硬盘位置无关,那么你的java进修将会进展的很顺遂.当你要装载资本的时辰,好比一些属性和设置装备摆设文件,尽可能的使用ResourceBundle.getBundle()而不是使用java.util.File,除非真的是必需这样.这样做不仅有利于你的J2EE应用开发,而且越到后来,你就越会发现,我怎媚暌剐那么多工具要装载?这个时辰,你就会感受这个体例确实给你带来了便利.尽管如斯,追寻到class的根阅暌剐时辰在轨范测试和debug的时辰会很有用,因为这个设法,我给出了一种很有辅佐的体例能够替我们完成这个使命,这些所有都是基于j2se的api的.
  /**
  * Given a Class object, attempts to find its .class location [returns null
  * if no such definition can be found]. Use for testing/debugging only.
  *
  * @return URL that points to the class definition .
  */
  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 ();
  // java.lang.Class contract does not specify if ‘pd‘ can ever be null;
  // it is not the case for Sun‘s implementations, but guard against null
  // just in case:
  if (pd != null)
  {
  final CodeSource cs = pd.getCodeSource ();
  // ‘cs‘ can be null depending on the classloader behavior:
  if (cs != null) result = cs.getLocation ();if (result != null)
  {
  // Convert a code source location into a full class file location
  // for some common cases:
  if ("file".equals (result.getProtocol ()))
  {
  try
  {
  if (result.toExternalForm ().endsWith (".jar")
页: [1]
查看完整版本: JAVA技巧:如何寻找一个类X实例中类的物理所在?