Java 如何在eclipse中调用.jar文件中的方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21011309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a method in .jar file in eclipse?
提问by lwang456
I have a jar file named Stdlib.jar and I have already imported into the project that I'm currently working on (using Build path in Eclipse). I have checked that the .jar file appears in the "Reference Libraries", but I'm not able to call the method that lies in the class of the .jar library.
我有一个名为 Stdlib.jar 的 jar 文件,并且我已经导入到我当前正在处理的项目中(使用 Eclipse 中的构建路径)。我已检查 .jar 文件是否出现在“参考库”中,但我无法调用位于 .jar 库类中的方法。
I searched a lot and here are my questions. Do I need to write a import statement in addition to the build path to use the method? If so, what is the syntax? (Because I did "add external jar", the .jar file is on my desktop. So should I write "import desktop/stdlib.jar;"?)
我搜索了很多,这里是我的问题。除了构建路径之外,我是否需要编写导入语句才能使用该方法?如果是这样,语法是什么?(因为我做了“添加外部jar”,.jar文件在我的桌面上。所以我应该写“import desktop/stdlib.jar;”吗?)
I used to do it on Linux and it was pretty easy with flag "cp- filepath". But when I came to Eclipse, I had no clue how to utilize an external library. Thank you very much for any kind of help!
我曾经在 Linux 上这样做过,使用标志“cp-filepath”很容易。但是当我使用 Eclipse 时,我不知道如何使用外部库。非常感谢您的任何帮助!
采纳答案by Seyed Mohammad
I'm not sure what your JAR file is (sounds like a JavaINI interface to C Std-Lib), but in any case, when you add a JAR file to a Java project in any IDE (Eclipse, Netbeans, etc) to be able to use the functionality provided by the JAR you must import the desired classes from the desired packages.
我不确定您的 JAR 文件是什么(听起来像是 C Std-Lib 的 JavaINI 接口),但无论如何,当您将 JAR 文件添加到任何 IDE(Eclipse、Netbeans 等)中的 Java 项目时要使用 JAR 提供的功能,您必须从所需的包中导入所需的类。
The general syntax is like this:
一般语法是这样的:
// To just add a specific class:
import packagename.ClassName;
// Or simply add all the classes in the package:
import packagename.*;
And these imports should come at the top of your Java source file.
这些导入应该位于 Java 源文件的顶部。
Then you can use the methods like this:
然后你可以使用这样的方法:
// For static methods:
ClassName.staticMethod(params);
// For non-static methods, first create an object:
ClassName obj = new ClassName(params);
// then call the desired methods:
obj.method(params);
Here is the "Using Packages" section of the Java-Tutorial: Using Packages
这是 Java 教程的“使用包”部分: 使用包
Also here are two similar question/answers on StackOverflow:
StackOverflow 上还有两个类似的问题/答案:
回答by Damith
Add the jar as reference and import the class or library into your class. Then create a object of a class if it is not static and access the method if it is public..
添加 jar 作为参考并将类或库导入到您的类中。然后创建一个类的对象,如果它不是静态的,如果它是公共的,则访问该方法。