简体   繁体   中英

Comparing values from common class in different jar

I have two java jar applications. There is a class called CommonClass that holds an enumeration :

public class CommonClass {

    public enum myEnum {

        NAME(0), TYPE(1), DESCRIPTION(2), OPTIONAL(3);
        private int value;

        private myEnum(int value) {
            this.value = value;
        }

        public int getValue() {
            return this.value;
        }
    }

}

The first jar has this class (first.jar.CommonClass) , and the second has it somewhere (any.package.CommonClass).

While running the first application, I would like at some point to compare the myEnum values. I am able load an instance of the main class from the second application class by parsing the manifest so I can find the main class name.

In theory, I would like to do :

if( any.package.CommonClass.myEnum.NAME.getValue() == first.jar.CommonClass.myEnum.NAME.getValue() ) {
    // Do something
}

How can I do that?


EDIT 1

The thing is : the first application is some kind of platform that is supposed to read unknown plugins. Those plugins should be developped following some conventions for compatibility. However there is no way of telling in which package the plugin developer wants to put the CommonClass.

The second application is such a plugin. To find and load its main class I parse the manifest. On practice I don't know the path of the CommonClass.

That is why I cannot import any package, because firstly I do not know which plugin will be used, and secondly I know even less about the CommonClass location in the jar file.

The easiest way to to it is to include both jars in your class path and just use the code you have posted in your question.

If for some reasons, that's not an option, and hence the type is not available at compile-time you would need Reflection. However, you don't need to parse the manifest nor load the main-class from a jar file just to access an enum class out of the jar. You can access the enum class via the same ClassLoader you have used to load the second main class skipping loading of the main-class:

ClassLoader loader; // the loader you have used for your second jar’s main class
Class<?> second=loader.loadClass(typeName);
assert second.isEnum();
Object enumConst=Enum.valueOf(second, "NAME");
int value=(Integer)second.getMethod("getValue").invoke(enumConst);

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