简体   繁体   中英

Using External library in java

I am using a Java external library, a .JAR file that contains a number of classes.

I Have two questions:

  1. I have a problem when using classes in the .JAR file. The problem is when some variables is defined in the class itself, how can I access it? Does the class in the .JAR itself finds it automatically or I should call it?

  2. I would like to know which is best to do: using an external library .JAR file or creating the classes and methods included in the .JAR file and include them in the project I am working on assuming that I have both the source code .JAVA files and the .JAR file of the classes I need to use?

Consider the code below, it is from an external project that I want to use in a current project, I have both .JAR and .JAVA files.
For example the code below has a variable named original_executer that is defined outside this method. If I call this method and give it the required string, will it do its function properly or an error will rise?

public boolean readSet(String setName){
    testSet = testSetName;
    OriginalLoader myLoader = new OriginalLoader();
    original_executer = myLoader.loadTestClass(testSet);
    original_obj = original_executer.newInstance();
    if(original_obj==null){
        System.out.println(" Can't instantiate original object");
        return false;
    }
    return true
}

If you add the .jar to your classpath, you can use everything as if it was defined in your project.

If your .jar file is a external library it is best to keep the library in the .jar and use it from there. Whenever the library gets updated, you can just overwrite the libraries .jar.

given your jar is properly added in the classpath and you have used the necessary imports in your code you can use any class or variables with correct modifier of the jar...

best is to use the external library as jar..and to consume it through package dependency tool like Maven which will automatically download the latest version of jar for you. And then you can compile and run against the latest version

To access the variables defined in the class, you would need to use the getter methods that are supplied. Otherwise, you would need to employ Reflection to grab the values by doing something like

Class.getClass().getField("field_name").set(Class.getClass(), "value");

Although I'm not 100% sure on the validity of that, I'm sure it is something along those lines.

For the second question, I'm not quite sure what you're asking but you should always just add the .jar file to the classpath or if you want to modify the library, download the source code of it and put it into your workspace.

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