Resolving class name conflicts in java

I have a situation where I have to load a named class. If there are several classes with the same name in my class (e.g. com.example.myclass), I should load both. I use the loadClass () method of my CustomLoader class, which comes from java.lang.ClassLoader. I have not changed the behavior of the parent class, but just call the parent methods. My problem is that if there are two classes with the same name, I can only load one of them. I looked at the web solution but could not find it. I found many solutions for reloading classes by creating a new instance of the class loader, but in my case, the new instance will probably load the first class again. Can this problem be solved?

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

EDIT: Both John and Stephen gave the same solution, but I can only mention one answer. Sorry :( I even voted for both answers.

+3
source share
3 answers

I believe that the JVM and class libraries assume that the class name is unique in the class loader. Therefore, if you want to load the same class name for different classes, you will need different class loaders (for example, one for each jar file).

Using them can be complicated, but this problem arises with such things.

+6
source

The classloader API is not able to specify which of the two classes with the same name your application is trying to load.

. , loadClass(String) .

"", . , , .

+4

, - . ? - , .

, ? ?

0

Source: https://habr.com/ru/post/1766519/


All Articles