首页 > csdn导入, 技术 > ClassLoader与Ant的一些问题

ClassLoader与Ant的一些问题

今天被这个Classloader搞死了。起因是这样的:

public  static void  staticMethod(){
String resource = ClassLoader.getSystemResource(“a.xml”).toString();
}
然后a.xml已经加入了CLASSPATH。
整个代码是写在一个Ant的Task里,然后Ant里调用(事先<taskdef>)

这个时候在Eclipse调用build.xml,没有问题。
但是在命令行下调用ant,出错,找不到,返回null。

于是到Task里的execute里测试一下
public void execute(){
String resource = getClass().getClassLoader().getResource(“a.xml”).toString();
}
两个环境都找到了。

看来是static的函数里ClassLoader比较不一样,是systemClassLoader估计。

然后这么写:
public  static void  staticMethod(){
String resource = new Object().getClass().getClassLoader().getResource(“a.xml”).toString();
}
居然报出一个NullPointerException,原来是返回的ClassLoader为空。马上查了一下ClassLoader的源码(IBM JDK),发现如果某个instance的classloader=systemClassLoader就返回空。什么道理啊。。。

这么写,也不行
public static void staticMethod(){
String resource = ClassLoader.getSystemClassLoader().getResource(“a.xml”).toString();
}

这么写,还是不行
public static void staticMethod(){
String resource = ClassLoader.getSystemClassLoader().getParent().getResource(“a.xml”).toString();
}

嗯,把那个类换成Singleton,发现居然可以了。
后来发现要这么写:
public class Test{
public static void staticMethod(){
String resource = new Test().getClass().getClassLoader().getResource(“a.xml”).toString();
}
}
才OK。。。

Eclipse自已有ClassLoader,Ant自己又有ClassLoader。才有这么多问题。
接下来我想搞的OSGi,每个Bundle都有自己的classloader实例。。。。晕死了。。。

分类: csdn导入, 技术 标签: , ,
  1. 本文目前尚无任何评论.
  1. 本文目前尚无任何 trackbacks 和 pingbacks.

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word


Warning: fsockopen() has been disabled for security reasons in /home/onlymars/public_html/wp/wp-includes/class-snoopy.php on line 1148