Well, I've been dealing with a big problem. I have two classes which has same class name and package structure they are present in two different jars for sure.
When I call a method of one class say for example setName.
I get an exception saying noSuchMethod; what can be the possible soluntion in this regard.
As classes are in jars I cant make any changes to them.
There is nothing like trying, either you do it or you don't.
It's going to be tricky, and dirty, and it will make your code very confusing. Only use it when you really don't have any other option. Can you first explain why the two jars contain classes with the same name, and whether the classes are actually the same, or if they perform different functions? A bit more detail about your project would be helpful.
Joined: Mar 12, 2008
well, to reply your question those classes are nt identical and having the same class name and package structure is out of my control.
In this case you might want to build a wrapper class for the class you want to use. The idea is that you first create a custom class loader that finds the specific class you want. You can then create instances of this class and call methods on it reflectively through the Class object. Create a wrapper class that delegates to these reflective method calls, so it will make the rest of your code easier to use.
I will try to flesh out an example wrapper for you, so you can see what I mean.
The Wrapper class below is *broken*. Do not use it. The class loader it uses will not be able to locate classes referenced by the wrapper class.
Instead, it's better to create a custom class loader at start up, that takes the responsibility of finding all the classes the program references, and keeping the two conflicting classes separateed.
Let's say we have two different classes with the same name, in two different Jars:
The first one is located in Lib1.jar, the second one is located in Lib2.jar. Both are in the classpath.
In my case, I can't use the second class, because the first one is being loaded by the class loader:Invoking this program will give me a NoSuchMethodException, if I get it to compile in the first place. So if I want to use the second class, I have to write a wrapper class for it:
This wrapper provides exactly the same methods as the class I want to use, and it provides a factory class that can provide instances of the wrapper class. Using this class works as follows: