开发者

resolving class name clashes in java

I have a situation where I have to load a named class. If there are multiple classes with the same name (say, com.example.myclass) in my class path I have to load both. I am using 'loadClass()' method of my CustomLoader class which derives from java.lang.ClassLoader. I have not changed the behaviour of the parent class but am simply calling the parent's methods. My problem is that if there are two classes with the same name, I am able to load only one of them. I have scanned the 开发者_如何学编程web for a solution but haven't found any. I found many solutions on reloading classes by creating a new class loader instance but in my case the new instance will probably end up loading the first class again. Can this problem be solved?

EDIT: I forgot to mention that the two classes with the same name are in different jar files.

EDIT: Both Jon and Stephen gave the same solution but I can mark only one as answer. Sorry :(. I have up voted both answers though.


I believe the JVM and class libraries assume that a class name is unique within a classloader. Therefore if you want to load the same class name for different classes, you'll need different classloaders (e.g. one for each jar file).

Using them could be tricky, but that's the sort of problem you get with this sort of thing.


The classloader API has no way to specify which of the two classes with the same name that your application is trying to load.

You will need to configure two different classloaders with different classpaths. Then you will need to load the classes by calling the loadClass(String) method on the respective classloaders.

There are a number of "gotchas" with doing this kind of thing. One of them is that the types of the instances of the respective classes will be different, and typecasts from one type to the other will fail.


I suggest that there is something seriously wrong with the problem here. How can such a state of affairs possibly come about in the first place? There is something seriously wrong with a development process that can produce duplicate classes in the first place.

Or is that the problem that this is trying to solve? Or diagnose?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜