简体   繁体   中英

Java JAR unable to load class on Class-Path?

I have a jar file that uses a class within a second jar file. However, when I run the first jar file, I get an exception that the class can not be found. I can't find any documentation on how to troubleshoot the issue.

I have two .jar files, MyApp.jar and sqljdbc42.jar. Both of these .jar files are in the same directory.

MyApp.jar has the following code in the main:

Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

The manifest for MyApp.jar has the following:

Manifest-Version: 1.0
Main-Class: com.mycompany.myapp.MyApp
Class-Path: sqljdbc42.jar
<blank line>

The class com.microsoft.sqlserver.jdbc.SQLServerDriver is in the jar sqljdbc42.jar.

When MyApp.jar is executed, the following exception occurs:

java.lang.ClassNotFoundException: com.microsoft.sqlserver.jdbc.SQLServerDriver
  at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
  at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
  at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
  at java.lang.Class.forName0(Native Method)
  at java.lang.Class.forName(Class.java:264)

Using Java 8, built in IntelliJ, verified the manifest contents by opening the jar in 7Zip. Any advice on how I can get this (seemingly simple, basic piece of Java JAR concept) working would be greatly appreciated.

There are three ways to solve your issue:

1) You can generate your jar using IDE " Eclipse Neon ".

  • create folder in your project "lib" and put sqljdbc42.jar into it;

  • add sqljdbc42.jar to the classPath: Properties -> Java Build Path -> Libraries -> Add JARs... (select your jar from "lib");

  • Right click on your project -> Export... -> Runnable JAR file -> Launch configuration (choose you main class) and check Library handing: Extract required libraries into generated JAR .

Eclipse will repack all reference libraries automatically without any security issues and ClassNotFound exceptions.

2) We should convert project into Maven project. And then use special plugins for generating JARs and creating dependencies of custom libs.

3) We can even generate it using Intellij Idea. But we should create Artifact of application with configuration where all signed libraries will be outside of your generated jar.

I think that the first variant is the easiest. Check it. If it does not help I will describe other methods with more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM