Java:如何使用第三方库?

hhh*_*hhh 3 java guava

代码显示使用-cp触发器编译但未运行.显然,它无法找到HashMultimap.类路径问题?

$ 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
Run Code Online (Sandbox Code Playgroud)

MultiMap的API.

bra*_*ter 6

就导入和编译而言,Java中的包不是分层相关的 - 例如,您无法com.google.collections.*通过导入导入com.*.

您提到的集合库中的包是:

com.google.common.core.*

com.google.common.annotations.*

com.google.common.collect.*

尝试显式导入这些包.如果你使用像Eclipse这样的IDE,它可以为你整理所有的import语句.


响应更新:-cp覆盖您的类路径.您需要包含当前目录以保留您在类路径上编写的类,因此假设您在类的目录中运行,请按如下方式设置类路径java -cp .:google-collect-1.0.jar MultiThing