【问题标题】:Java: how to use 3rd-party library?Java:如何使用 3rd-party 库?
【发布时间】:2015-09-16 09:42:44
【问题描述】:

代码显示使用 -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

API for MultiMap.

【问题讨论】:

  • 将源代码发布到您的 multitest.java 此处作为对原始问题的更新

标签: java guava


【解决方案1】:

就导入和编译而言,Java 中的包没有层次相关 - 例如,您不能通过导入 com.* 来导入com.google.collections.*

您提到的收藏库中的包是:

com.google.common.core.*

com.google.common.annotations.*

com.google.common.collect.*

尝试显式导入这些包。如果您使用的是 Eclipse 之类的 IDE,它可以为您整理出所有的导入语句。


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

【讨论】:

  • " 如果您使用 Eclipse 之类的 IDE,它可以为您整理所有导入语句。" ...这就是 java 正在消亡的原因。
【解决方案2】:

除了关于将 JAR 添加到类路径中的说法之外:我没有使用 Google Collections,但我非常怀疑他们将类放在名为 com 的包中。

您应该知道,对于嵌套包,import level1.* 不会导入包 level1.level2 中的任何类。

因此,对于您的示例,您需要将 import com.* 更改为 import com.google-collections.whateverpackageyouneed.*。根据 Google Collections API 进行修改。

【讨论】:

    【解决方案3】:

    您通常将 3rd 方包作为 jar 文件(java 存档)获取,然后是 add it to your classpath during compilation and while executing the Java process

    在 Unix 和 Windows 中执行此操作的语法略有不同。如果您使用 Eclipse 之类的 IDE,有多种方法可以将 jar 添加到构建中。

    如果您使用的是 Google 集合,您下载的 zip 文件中应该有一个 jar。像 google-collect*.jar 之类的东西

    更新:看起来 OP 修改了问题

    【讨论】:

      猜你喜欢
      • 2017-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      • 2019-04-21
      相关资源
      最近更新 更多