toddeTV
toddeTV

Reputation: 1517

Exclude class or package inside classpath when starting an application

I have multiple *.jar files inside a folder, that are all included in the classpath in order to start the specified main class in Microsoft Windows OS. This is currently accomplished like this:

@echo off
java -Xmx1024M -cp libs/*;. org.test.Main

Now I have the problem, that inside the libs folder there are two JAR files, that both have one same package org.test.configuration. Both are different and when I now start the program, I get errors because the wrong one is selected by the Java VM.

How can I exclude one special Package or one special Class within my start script? (Of course I could delete this package out of the wrong jar, but I do not want to use this method...)

Upvotes: 2

Views: 14698

Answers (1)

AJNeufeld
AJNeufeld

Reputation: 8695

Java searches the class path for packages/classes in order. Instead of using a wildcard ...

java -Xmx1024M -cp libs/*;. org.test.Main

... write out the class path in the order desired, with the jar containing the "correct" org.test.configuration package first.

java -Xmx1024M -cp libs/test-config.jar;libs/other.jar;libs/etc.jar;. org.test.Main

Edit

You might be able to get away still using the wildcard, by just explicitly listing the desired jar first, and letting it get duplicated in the classpath:

java -Xmx1024M -cp libs/test-config.jar;libs/*;. org.test.Main

Here is a Minimal, Complete, Verifiable Example:

org\test\Main.java (in main.jar):

package org.test;

import org.test.configuration.Config;

public class Main {

    public static void main(String[] args) {
        Config cfg = Config.getConfig();
        System.out.println(cfg);
    }
}

org\test\configuration\Config.java (in config1.jar):

package org.test.configuration;

public class Config {
    public static Config getConfig() {
        return new Config();
    }
}

org\test\configuration\Config.java (in config2.jar):

package org.test.configuration;

public class Config {
    public static Config getConfig() {
        return null;
    }
}

java -cp libs\*;. org.test.Main
org.test.configuration.Config@1540e19d

java -cp libs\config2.jar;libs\*;. org.test.Main
null

Using just libs\* in the classpath resulted in config1.jar being included first, and a live Config object was returned. Using libs\config2.jar;libs\* resulted in Config from config2.jar being included first, and null was returned.

Upvotes: 4

Related Questions