Java: how to use a third-party library?

The code shows compilation using -cp trigger, but does not work. Apparently he cannot find the HashMultimap. Problem with the class?

$ javac -cp google-collect-1.0.jar  MultiThing.java 
$ java -cp google-collect-1.0.jar MultiThing 
Exception in thread "main" java.lang.NoClassDefFoundError: MultiThing
Caused by: java.lang.ClassNotFoundException: MultiThing
    at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:319)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:264)
    at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:332)
Could not find the main class: MultiThing. Program will exit.
$ cat MultiThing.java 
import java.io.*;
import java.util.*;
import com.google.common.annotations.*;
import com.google.common.collect.*;

public class MultiThing {
    public static void main(String[] args) {
        Multimap<String, String> wordToFiles = HashMultimap.create();
        wordToFiles.put("first", "HELLO");
        wordToFiles.put("first", "HALLO");
        for (String thing : wordToFiles.get("first")){
            System.out.println(thing);
        }
    }
}
$ ls
google-collect-1.0.jar  MultiThing.class   com     MultiThing.java

API for MultiMap.

+3
source share
3 answers

Packages in Java are not hierarchically related in terms of import and compilation - for example, you cannot import com.google.collections.*by import com.*.

Packages in the collection library that you mentioned:

com.google.common.core.*

com.google.common.annotations.*

com.google.common.collect.*

Try importing these packages explicitly. If you use an IDE like Eclipse, it can sort all your import statements for you.


: -cp . , , , , , , : java -cp .:google-collect-1.0.jar MultiThing

+6

jar (java-), Java.

Unix Windows. IDE, Eclipse, .

Google, zip . - google-collect *.jar

: ,

+1

In addition to what was said about adding a JAR to your classpath: I have not used Google Collections, but I highly doubt that they put their classes in a package called com.

You should be aware that for nested packages, import level1.*none of the classes in the package will import level1.level2.

So, for your example, you will need to change import com.*to import com.google-collections.whateverpackageyouneed.*. Change according to the Google collections API.

+1
source

Source: https://habr.com/ru/post/1739867/


All Articles