I created a JAR file and then added it to my project's build path. Now how do I import it to my class so I can use it? I've only tried import java-class.jar;
so far.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You import classes, not jar files, in your Java source code.
Lets assume you have
someJar.jar
which contains class definitions for 3 classes,FirstClass.class
,SecondClass.class
andThirdClass.class
, all of which are in packageorg.somepackage
.Given the above, you would add
at the top of a source file to import the class called
FirstClass
.Once the jar is on the execution class path, you import them normally :
This is because the Java virtual machine has the concept of a "class path". This class path is filled with all files (classes and resources) found in jar files and folders placed on the classpath.
For example, if you have two jar and one folder :
From the JVM POV you have the sum of all these folders, as if they were in a single folder.
So you can freely import whatever class you need, specifying the fully qualified name, independently if it is inside a jar or in your project bin folder.
In fact jars are nothing more than zip files of folders, containing compiled classes (and eventually other resources).
The class path is declared to the JVM when running a program, using the "-cp" command line switch. For example, for the previous 2 jars and one folder, on windows, you would write :
After adding jar to projects build path you can import classes specifically or you can import java class packages. See the following two examples.
Suppose you want to use some functions of Scanner class in your own class. Then you have to import Scanner class in to your class.(Remember there are lot more other classes in the same package with the Scanner class).
To import the Scanner class specifically from util package you can use following syntax.
This will import only the Scanner class from the util package and allow only to use functions of the Scanner class.
To import all the classes in the util package you can use following syntax
This will import all the classes in the util package and you are allowed to use any functionality from any class in your class (not only functions of the Scanner class).
The second method is called as
wildcard import
.There is no performance difference between a specific import and a wildcard import declaration.You cannot import .jar file.
To do this, you need to add it to the classpath when compiling and running, like
java -cp myJar.jar a.b.myMainClass
or
javac -cp myJar.jar a/*