Java: Two jars in project with same class. - java

I have a java project that is using two imported jars with the same class (com.sun.mail.imap.IMAPFolder). Is there a way to explicitly say which jar to use when importing the class? Using:
import com.sun.mail.imap.IMAPFolder;
would seem to use the class in order of build path order but this does not seem to be the case for some reason causing
Exception in thread "main" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.NoSuchMethodError: com.sun.mail.imap.IMAPFolder.idle()V
at com.woodbury.GCM.HelperGmailMonitor.doEmail(HelperGmailMonitor.java:104)
at com.woodbury.GCM.Launch.listen(Launch.java:16)
at com.woodbury.GCM.Launch.main(Launch.java:10)
... 5 more
at runtime. I am building the project in eclipse.

When a class is loaded, the first implementation that matches the requested fully qualified name that is visible to the relevant ClassLoader is what gets returned. Any other implementations with the same fully qualified name are effectively hidden to that ClassLoader.
What this means in a standard Java SE application is that the first code base (e.g. a jar) listed on the classpath with the required class, provides it, and all other code bases' implementations of the same fully qualified class are hidden.
Example:
Assume that A.jar contains the compiled class
package com.stackoverflow.example;
public class Hello {
public static String getGreeting(){
return "Hello, A!"
}
}
Assume that B.jar contains the compiled class
package com.stackoverflow.example
public class Hello {
public static String getGreeting(){
return "Hello, B!"
}
}
Note that in both of the above classes have the same fully qualified name.
Assume main class is
import com.stackoverflow.example.Hello;
public class ExampleMain {
public static void main(String[] args){
System.out.println(Hello.getGreeting());
}
}
If I were to invoke my program with
java -cp A.jar:B.jar ExampleMain
the output is: Hello, A!
If I reverse the classpath like so
java -cp B.jar:A.jar ExampleMain
the output is: Hello, B!

You cannot do what you ask just in your Java source. Java was not designed for that.
This is a bad situation which can only be handled reliably with custom class loaders, each providing one of the jars you need. Since you are asking this question in the first place this is probably not the way you should go yet since that opens up a LOT of new time consuming problems.
I would strongly suggest you find out why you have two different versions of the same jar in your classpath and rework your program so you only need one version.

Yes, there is a way to fix the issue. In my scenario, I have two classes with same name and same path and eclipse always imports the wrong one. What I have done is changing the jar order in the build path and eclipse will pick the first one in the build path.

If you are using an IDE, you can set the order of exporting the files to the class loader.
I work on eclipse and I use maven. When I install the project using maven, it produced many extra jars (which i hadnt defined in my dependencies) and there was a file org.w3c.dom.Element which was present in 2 jar files and 3rd instance of the same file was also in JRE7.
In order to make sure the correct file is picked up, all I had to do was to go to Java Build Path -> Order and Export. Select the Jar file I wanted the classloader to give more preference and move it up with the button "Up".
This is how it looks.
Please note that this image is for eclipse. But for other IDEs there would definitely be a similar way to work this out.

1) In general: Yes you can have the same class in different .jar files: you just disambiguate them with a fully qualified package name. The "Date" class (present in java.util and java.sql) is a good example.
2) If you have two DIFFERENT .jar files that have the SAME fully qualified package names ... chances are, you've got a conflict. Even if you can hack around the InvocationTargetException by playing with the class loader, you might still encounter other problems. In this case, it sounds like maybe your two .jar files have two different implementations of the JavaMail API. I don't know.
3) The safest bet is to satisfy all your program's references WITHOUT risking a conflict. I believe if you took took the "official" .jar's from Oracle's JavaMail web page, you can do this:
https://java.net/projects/javamail/pages/Home
'Hope that helps!

Related

Java Subclass being brought in through classpath not able to find parent [duplicate]

I am getting a NoClassDefFoundError when I run my Java application. What is typically the cause of this?
While it's possible that this is due to a classpath mismatch between compile-time and run-time, it's not necessarily true.
It is important to keep two or three different exceptions straight in our head in this case:
java.lang.ClassNotFoundException This exception indicates that the class was not found on the classpath. This indicates that we were trying to load the class definition, and the class did not exist on the classpath.
java.lang.NoClassDefFoundError This exception indicates that the JVM looked in its internal class definition data structure for the definition of a class and did not find it. This is different than saying that it could not be loaded from the classpath. Usually this indicates that we previously attempted to load a class from the classpath, but it failed for some reason - now we're trying to use the class again (and thus need to load it, since it failed last time), but we're not even going to try to load it, because we failed loading it earlier (and reasonably suspect that we would fail again). The earlier failure could be a ClassNotFoundException or an ExceptionInInitializerError (indicating a failure in the static initialization block) or any number of other problems. The point is, a NoClassDefFoundError is not necessarily a classpath problem.
This is caused when there is a class file that your code depends on and it is present at compile time but not found at runtime. Look for differences in your build time and runtime classpaths.
Here is the code to illustrate java.lang.NoClassDefFoundError. Please see Jared's answer for detailed explanation.
NoClassDefFoundErrorDemo.java
public class NoClassDefFoundErrorDemo {
public static void main(String[] args) {
try {
// The following line would throw ExceptionInInitializerError
SimpleCalculator calculator1 = new SimpleCalculator();
} catch (Throwable t) {
System.out.println(t);
}
// The following line would cause NoClassDefFoundError
SimpleCalculator calculator2 = new SimpleCalculator();
}
}
SimpleCalculator.java
public class SimpleCalculator {
static int undefined = 1 / 0;
}
NoClassDefFoundError In Java
Definition:
Java Virtual Machine is not able to find a particular class at runtime which was available at compile time.
If a class was present during compile time but not available in java classpath during runtime.
Examples:
The class is not in Classpath, there is no sure shot way of knowing it but many times you can just have a look to print System.getproperty("java.classpath") and it will print the classpath from there you can at least get an idea of your actual runtime classpath.
A simple example of NoClassDefFoundError is class belongs to a missing JAR file or JAR was not added into classpath or sometimes jar's name has been changed by someone like in my case one of my colleagues has changed tibco.jar into tibco_v3.jar and the program is failing with java.lang.NoClassDefFoundError and I were wondering what's wrong.
Just try to run with explicitly -classpath option with the classpath you think will work and if it's working then it's a sure short sign that someone is overriding java classpath.
Permission issue on JAR file can also cause NoClassDefFoundError in Java.
Typo on XML Configuration can also cause NoClassDefFoundError in Java.
when your compiled class which is defined in a package, doesn’t present in the same package while loading like in the case of JApplet it will throw NoClassDefFoundError in Java.
Possible Solutions:
The class is not available in Java Classpath.
If you are working in J2EE environment than the visibility of Class among multiple Classloader can also cause java.lang.NoClassDefFoundError, see examples and scenario section for detailed discussion.
Check for java.lang.ExceptionInInitializerError in your log file. NoClassDefFoundError due to the failure of static initialization is quite common.
Because NoClassDefFoundError is a subclass of java.lang.LinkageError it can also come if one of it dependency like native library may not available.
Any start-up script is overriding Classpath environment variable.
You might be running your program using jar command and class was not defined in manifest file's ClassPath attribute.
Resources:
3 ways to solve NoClassDefFoundError
java.lang.NoClassDefFoundError Problem patterns
I have found that sometimes I get a NoClassDefFound error when code is compiled with an incompatible version of the class found at runtime. The specific instance I recall is with the apache axis library. There were actually 2 versions on my runtime classpath and it was picking up the out of date and incompatible version and not the correct one, causing a NoClassDefFound error. This was in a command line app where I was using a command similar to this.
set classpath=%classpath%;axis.jar
I was able to get it to pick up the proper version by using:
set classpath=axis.jar;%classpath%;
One interesting case in which you might see a lot of NoClassDefFoundErrors is when you:
throw a RuntimeException in the static block of your class Example
Intercept it (or if it just doesn't matter like it is thrown in a test case)
Try to create an instance of this class Example
static class Example {
static {
thisThrowsRuntimeException();
}
}
static class OuterClazz {
OuterClazz() {
try {
new Example();
} catch (Throwable ignored) { //simulating catching RuntimeException from static block
// DO NOT DO THIS IN PRODUCTION CODE, THIS IS JUST AN EXAMPLE in StackOverflow
}
new Example(); //this throws NoClassDefFoundError
}
}
NoClassDefError will be thrown accompanied with ExceptionInInitializerError from the static block RuntimeException.
This is especially important case when you see NoClassDefFoundErrors in your UNIT TESTS.
In a way you're "sharing" the static block execution between tests, but the initial ExceptionInInitializerError will be just in one test case. The first one that uses the problematic Example class. Other test cases that use the Example class will just throw NoClassDefFoundErrors.
This is the best solution I found so far.
Suppose we have a package called org.mypackage containing the classes:
HelloWorld (main class)
SupportClass
UtilClass
and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).
The file structure will look like this:
When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command:
I was using Spring Framework with Maven and solved this error in my project.
There was a runtime error in the class. I was reading a property as integer, but when it read the value from the property file, its value was double.
Spring did not give me a full stack trace of on which line the runtime failed.
It simply said NoClassDefFoundError. But when I executed it as a native Java application (taking it out of MVC), it gave ExceptionInInitializerError which was the true cause and which is how I traced the error.
#xli's answer gave me insight into what may be wrong in my code.
I get NoClassFoundError when classes loaded by the runtime class loader cannot access classes already loaded by the java rootloader. Because the different class loaders are in different security domains (according to java) the jvm won't allow classes already loaded by the rootloader to be resolved in the runtime loader address space.
Run your program with 'java -javaagent:tracer.jar [YOUR java ARGS]'
It produces output showing the loaded class, and the loader env that loaded the class. It's very helpful tracing why a class cannot be resolved.
// ClassLoaderTracer.java
// From: https://blogs.oracle.com/sundararajan/entry/tracing_class_loading_1_5
import java.lang.instrument.*;
import java.security.*;
// manifest.mf
// Premain-Class: ClassLoadTracer
// jar -cvfm tracer.jar manifest.mf ClassLoaderTracer.class
// java -javaagent:tracer.jar [...]
public class ClassLoadTracer
{
public static void premain(String agentArgs, Instrumentation inst)
{
final java.io.PrintStream out = System.out;
inst.addTransformer(new ClassFileTransformer() {
public byte[] transform(ClassLoader loader, String className, Class classBeingRedefined, ProtectionDomain protectionDomain, byte[] classfileBuffer) throws IllegalClassFormatException {
String pd = (null == protectionDomain) ? "null" : protectionDomain.getCodeSource().toString();
out.println(className + " loaded by " + loader + " at " + new java.util.Date() + " in " + pd);
// dump stack trace of the thread loading class
Thread.dumpStack();
// we just want the original .class bytes to be loaded!
// we are not instrumenting it...
return null;
}
});
}
}
The technique below helped me many times:
System.out.println(TheNoDefFoundClass.class.getProtectionDomain().getCodeSource().getLocation());
where the TheNoDefFoundClass is the class that might be "lost" due to a preference for an older version of the same library used by your program. This most frequently happens with the cases, when the client software is being deployed into a dominant container, armed with its own classloaders and tons of ancient versions of most popular libs.
Java ClassNotFoundException vs NoClassDefFoundError
[ClassLoader]
Static vs Dynamic class loading
Static(Implicit) class loading - result of reference, instantiation, or inheritance.
MyClass myClass = new MyClass();
Dynamic(Explicit) class loading is result of Class.forName(), loadClass(), findSystemClass()
MyClass myClass = (MyClass) Class.forName("MyClass").newInstance();
Every class has a ClassLoader which uses loadClass(String name); that is why
explicit class loader uses implicit class loader
NoClassDefFoundError is a part of explicit class loader. It is Error to guarantee that during compilation this class was presented but now (in run time) it is absent.
ClassNotFoundException is a part of implicit class loader. It is Exception to be elastic with scenarios where additionally it can be used - for example reflection.
In case you have generated-code (EMF, etc.) there can be too many static initialisers which consume all stack space.
See Stack Overflow question How to increase the Java stack size?.
Two different checkout copies of the same project
In my case, the problem was Eclipse's inability to differentiate between two different copies of the same project. I have one locked on trunk (SVN version control) and the other one working in one branch at a time. I tried out one change in the working copy as a JUnit test case, which included extracting a private inner class to be a public class on its own and while it was working, I open the other copy of the project to look around at some other part of the code that needed changes. At some point, the NoClassDefFoundError popped up complaining that the private inner class was not there; double-clicking in the stack trace brought me to the source file in the wrong project copy.
Closing the trunk copy of the project and running the test case again got rid of the problem.
I fixed my problem by disabling the preDexLibraries for all modules:
dexOptions {
preDexLibraries false
...
I got this error when I add Maven dependency of another module to my project, the issue was finally solved by add -Xss2m to my program's JVM option(It's one megabyte by default since JDK5.0). It's believed the program does not have enough stack to load class.
In my case I was getting this error due to a mismatch in the JDK versions. When I tried to run the application from Intelij it wasn't working but then running it from the command line worked. This is because Intelij was attempting to run it with the Java 11 JDK that was setup but on the command line it was running with the Java 8 JDK. After switching that setting under File > Project Structure > Project Settings > Project SDK, it worked for me.
Update [https://www.infoq.com/articles/single-file-execution-java11/]:
In Java SE 11, you get the option to launch a single source code file
directly, without intermediate compilation. Just for your convenience,
so that newbies like you don't have to run javac + java (of course,
leaving them confused why that is).
NoClassDefFoundError can also occur when a static initializer tries to load a resource bundle that is not available in runtime, for example a properties file that the affected class tries to load from the META-INF directory, but isn’t there. If you don’t catch NoClassDefFoundError, sometimes you won’t be able to see the full stack trace; to overcome this you can temporarily use a catch clause for Throwable:
try {
// Statement(s) that cause(s) the affected class to be loaded
} catch (Throwable t) {
Logger.getLogger("<logger-name>").info("Loading my class went wrong", t);
}
I was getting NoClassDefFoundError while trying to deploy application on Tomcat/JBOSS servers. I played with different dependencies to resolve the issue, but kept getting the same error. Marked all javax.* dependencies as provided in pom.xml, And war literally had no Dependency in it. Still the issue kept popping up.
Finally realized that src/main/webapps/WEB-INF/classes had classes folder which was getting copied into my war, so instead of compiled classes, this classes were getting copied, hence no dependency change was resolving the issue.
Hence be careful if any previously compiled data is getting copied, After deleting classes folder and fresh compilation, It worked!..
If someone comes here because of java.lang.NoClassDefFoundError: org/apache/log4j/Logger error, in my case it was produced because I used log4j 2 (but I didn't add all the files that come with it), and some dependency library used log4j 1. The solution was to add the Log4j 1.x bridge: the jar log4j-1.2-api-<version>.jar which comes with log4j 2. More info in the log4j 2 migration.
This error can be caused by unchecked Java version requirements.
In my case I was able to resolve this error, while building a high-profile open-source project, by switching from Java 9 to Java 8 using SDKMAN!.
sdk list java
sdk install java 8u152-zulu
sdk use java 8u152-zulu
Then doing a clean install as described below.
When using Maven as your build tool, it is sometimes helpful -- and usually gratifying, to do a clean 'install' build with testing disabled.
mvn clean install -DskipTests
Now that everything has been built and installed, you can go ahead and run the tests.
mvn test
I got NoClassDefFound errors when I didn't export a class on the "Order and Export" tab in the Java Build Path of my project. Make sure to put a checkmark in the "Order and Export" tab of any dependencies you add to the project's build path. See Eclipse warning: XXXXXXXXXXX.jar will not be exported or published. Runtime ClassNotFoundExceptions may result.
It could also be because you copy the code file from an IDE with a certain package name and you want to try to run it using terminal. You will have to remove the package name from the code first.
This happens to me.
Everyone talks here about some Java configuration stuff, JVM problems etc., in my case the error was not related to these topics at all and had a very trivial and easy to solve reason: I had a wrong annotation at my endpoint in my Controller (Spring Boot application).
I have had an interesting issue wiht NoClassDefFoundError in JavaEE working with Liberty server. I was using IMS resource adapters and my server.xml had already resource adapter for imsudbJXA.rar.
When I added new adapter for imsudbXA.rar, I would start getting this error for instance objects for DLIException, IMSConnectionSpec or SQLInteractionSpec.
I could not figure why but I resolved it by creating new server.xml for my work using only imsudbXA.rar. I am sure using multiple resource adapters in server.xml is fine, I just had no time to look into that.
I had this error but could not figure out the solution based on this thread but solved it myself.
For my problem I was compiling this code:
package valentines;
import java.math.BigInteger;
import java.util.ArrayList;
public class StudentSolver {
public static ArrayList<Boolean> solve(ArrayList<ArrayList<BigInteger>> problems) {
//DOING WORK HERE
}
public static void main(String[] args){
//TESTING SOLVE FUNCTION
}
}
I was then compiling this code in a folder structure that was like /ProjectName/valentines
Compiling it worked fine but trying to execute: java StudentSolver
I was getting the NoClassDefError.
To fix this I simply removed: package valentines;
I'm not very well versed in java packages and such but this how I fixed my error so sorry if this was already answered by someone else but I couldn't interpret it to my problem.
My solution to this was to "avail" the classpath contents for the specific classes that were missing. In my case, I had 2 dependencies, and though I was able to compile successfully using javac ..., I was not able to run the resulting class file using java ..., because a Dynamic class in the BouncyCastle jar could not be loaded at runtime.
javac --classpath "ext/commons-io-2.11.0;ext/bc-fips-1.0.2.3" hello.java
So at compile time and by runtime, the JVM is aware of where to fetch Apache Commons and BouncyCastle dependencies, however, when running this, I got
Error: Unable to initialize main class hello
Caused by: java.lang.NoClassDefFoundError:
org/bouncycastle/jcajce/provider/BouncyCastleFipsProvider
And I therefore manually created a new folder named ext at the same location, as per the classpath, where I then placed the BouncyCastle jar to ensure it would be found at runtime. You can place the jar relative to the class file or the jar file as long as the resulting manifest has the location of the jar specified. Note I only need to avail the one jar containing the missing class file.
Java was unable to find the class A in runtime.
Class A was in maven project ArtClient from a different workspace.
So I imported ArtClient to my Eclipse project.
Two of my projects was using ArtClient as dependency.
I changed library reference to project reference for these ones (Build Path -> Configure Build Path).
And the problem gone away.
I had the same problem, and I was stock for many hours.
I found the solution. In my case, there was the static method defined due to that. The JVM can not create the another object of that class.
For example,
private static HttpHost proxy = new HttpHost(proxyHost, Integer.valueOf(proxyPort), "http");
I got this message after removing two files from the SRC library, and when I brought them back I kept seeing this error message.
My solution was: Restart Eclipse. Since then I haven't seen this message again :-)

What's the differences between the build function of Eclipse and javac?

I find a project in Eclipse has it own class path.
If i use maven create a new web project.
System.getProperty("java.class.path");
When i print the result,
I find the class path contains G:\newtool\workspace\springmvc\target\classes.
Who can explain the principles behind it.Why the class path is this directory.
Is the build function of Eclipse same as the command,javac -classpath?
And i find another question.
public class KnightMain {
public static void main(String[] args) throws Exception {
System.setProperty("java.class.path","G:/newtool/workspace;G:/newtool");
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("knight.xml");
Knight knight = context.getBean(Knight.class);
knight.embarkOnQuest();
String s[] = System.getProperty("java.class.path").split(";");
for (String string : s) {
System.out.println(string);
}
context.close();
}
}
Although i set the class path to other directory where the knight.xml is not exist.But ClassPathXmlApplicationContext find it finally.Why the
System.setProperty("java.class.path","G:/newtool/workspace;G:/newtool");
makes no difference.Although the print result is:
G:/newtool/workspace G:/newtool
Two different tools, two different concepts.
First of all eclipse has its own java compiler. It is not using javac in any way. And the class path used by the eclipse compiler, is, surprise, what you told it to be.
In other words: when you create your eclipse projects, you configure its build path. The Build Path determines which libraries, other projects, ... should be imported, exported, ... and so on.
Whereas, when you open your command like shell, and you call javac directly, the classpath is based on the settings that you make there; for example by calling
javac -classpath /some/directory/with/classes:/some/bla.jar
Or in your case: you are using maven, which comes with its pre-defined rules, project dependencies, and so on. Thus your classpath there depends on the conventions/rules that maven applies for "java web projects". Thus: if you want to understand what maven is doing for you: you have to study the maven documentation for the features you are using there!
EDIT: I think what you are actually trying can't work. I think that this specific system property is more of a "read only" value. Meaning: you can use it to understand the current classpath. But writing the property will not change the classpath of the JVM you are currently running in.
Actually, that makes a lot of sense: if any piece of java code could change the classpath on the fly, that screams "security problem" all over the place! As that would allow you to completely change where the JVM would be loading its classes from.
The java.class.path property is used by JVM to locate classes and JAR files for loading. This system property is common for most available JVMs including Oracle and IBM implementations. This property is used by the default class loader, but not all custom class loaders. You can implement your own class loader, that ignores java.class.path and is using some other property to locate loader-specific packages. One example is Eclipse. Eclipse core has a custom class loader that is not using java.class.path.

Same class is in multiple jar

I have several jars containing the exact same class.
Lets say for example, A.jar and B.jar have the same class Hello.class. What will happen if I run the following:
java -classpath A.jar;B.jar com.testing.testcode
My question is whether it will run or not? As from my understanding class loader will scan the classpath and it will return whatever Hello.class it finds first.
I know I can avoid this problem if I use OSGi for loading a particular class.
But what my question is – whether this will run or not? Or the java -classpath A.jar;B.jar com.testing.testcode will break down for having two version of the same class.
This will work and the first Hello class in the classpath will be used, so in this case, the one from the A.jar
The class path is a "path". The first match is taken.
There is a boot class path which is examined first and this included the JARs in the JRE. BTW You can prepend these and override system classes but you are not supposed to and it might not be allowed in your license agreement.
Whenever you include the jar in your classpath, on startup/ on application class gets loaded into the container.
Now whether your code will work or not will depend on which jar gets loaded first in your container and accordingly if you are lucky then in your current setup it will work else you might get some error saying that method1 doesn't accept Type1 it should accept Type2.

Load methods and classes from build bath in Java

I am using Eclipse and I have got two libraries included in my project, foo.jar and bar.jar. In both JARs there is a class FooBar.java that includes the method getFoobar(Object xy).
Now I would like to load the method getFoobar(Object xy) either from foo.jar or from bar.jar on the basis of a properties file:
config.properties:
choice=foo
If choice==foo then the method of Foo.jar shall be picked, elsewise the method getFoobar(Object xy) from Bar.java. To make things more complicated the method getFoobar(Object xy) has in its method declaration objects loaded from another JAR which is included in foo.jar (and bar.jar respectively).
So my question is. How can I get the methods of the JARs respectively by Reflections? I have not yet found a solution. Is there a way to solve this issue?
Thank you.
Emrah
You can only load one or the other methods without getting complicated with class loaders. A simple workaround is to rename the package of one or both libraries with jarjar This allows you to have everything in foo.jar start with foo. and everything is bar.jar start with bar. and this avoids any confusion. I have seen this used to be able to load several version of Xerces based on configuration (and use them concurrently in the same app)
Write your ClassLoader that reads the property. Alternatively, you can use -D option in the jvm arguments
-Dchoice=foo
and in the code that loads the class from foo.jar or from bar.jar you can switch on this property value:
String choice = System.getProperty("choice");
if (Main.CHOICE_FOO.equalsIgnoreCase(choice)) {...}
...
OSGI can give you a similar capability.
How can I get the methods of the JARs respectively by Reflections?
You can't.
Reflection does not allow you to select between the two versions of the class. In fact, as far as the JVM is concerned, there is only one version; i.e. the one that appears earliest on the classpath.
You can solve this problem by defining multiple classloaders, each with a different classpath. However, there are complications:
If you manage to load both versions of the class into a running application, you will find that instances of the respective classes have different types, and you won't be able to convince the JVM otherwise.
When your application loads another class that statically depends on one of these classes, it will bind to the version of the class that is on the classpath of the dependent classes classloader. And you can't change that. So, uses of the class name in declarations / typecasts / etc in the dependent class will refer to the version of the class found by the dependent classes classloader, not the other one.
The upshot is that you can't use these same-named classes like regular classes ... especially if both versions need to be loaded in the same JVM. It is a better idea to give the two versions of the class different names. You don't gain anything by making the class names the same.

how to avoid "duplicate class" in Java

Suppose I have have a java project myProject and am using an external library jar (someJar.jar), which has a class com.somepackage.Class1.class.
Now I find an updated version of Class1.java which fixes a bug in the original jar.
I include the new Class1.java in my source code under package com.somepackage
When I build the project (e.g., using Netbeans), there is a dist\myProject.jar which contains the classcom.somepackage.Class1.class and a dist\lib\someJar.jar which also contains a class with the same name.
When I run the file (e.g, using java -jar dist\myProject.jar), the new version of Class1.class is used (as I want).
How does Java decide which class file to run in case of such duplicates? Is there any way I can specify precedence ?
Is there any 'right' way to avoid such clashes?
In Proguard, when I try to compress my code, I get a duplicate class error. How do I eliminate this?
Java decides which one to use based on the order of the classpath. List yours first and you'll be fine.
The "right" way would be to fix the orignal source, but sometimes that's not always an option.
I haven't used ProGuard, but I have re-jarred libaries before that had duplicate classes. The solution in my case was to tell Ant to ignore duplicate classes. I would assume ProGuard would have that support too.
Can you not create an updated jar file which contains the bug fix? It's going to make things a lot simpler if you don't have two versions of the same fully-qualified class around.
1) Updated Jar is a better solution.
2) Use a different class name. Is there a reason, why you want to use the same class name and same packing? I don't think there is a reason.
3) create a wrapper/ proxy class, that encapsulate all the calls to the jar and you can decide to call this new class that fixes the bug ( provided it has a different name and packaging)

Categories