I have a jar called "MyTools". The jar is in c:\data folder. I created a new file in the same folder called "UseTools.java". Now I would like to use some of the classes from the MyTools.jar in my UseTools.java. I tried this but it doesnt seem to work:
import MyTools.*;
public class UseTools
{
public static void main(String[] args)
{
MyTools.SomeClass foo = new SomeClass();
SomeClass.doSomething();
}
}
I tried to compile this with:
javac -cp . UseTools.java
and got this error message:
UseTools.java:1: package MyTools does not exist
import MyTools.*;
^
UseTools.java:7: package MyTools does not exist
MyTools.SomeClass foo = new SomeClass()
^
2 errors
I did not set the package name in any class.
Do I have to set a package name in my jar classes?
List Files. List all the files inside the JAR without extracting it. This can be done using either command jar , unzip or vim . Using unzip command in normal mode: list ( -l ) archive files in short format.
JAR files are packaged in the ZIP file format. In other words, if a utility can read a ZIP file, we can use it to view a JAR file as well. The unzip command is a commonly used utility for working with ZIP files from the Linux command-line.
To mention something that relates more to the title of the question: In Java, you can't access classes in the default package from code within a named package.
This means, if the classes in your jar file do not belong explicitly to any package and inside the jar your files are directly in the root folder without subfolders, they are in the default package. This is not very elaborated and lacks modularity as well as extensibility, but is technically alright. Then, you can only use these classes from code which also is in the default package. But this does not necessarily mean it has to be in the same jar. If you have multiple src or class folders they could all contain classes in the default package which can interact. The organization in JAR files and the package structure in your project are independent of each other.
However, I'd strictly encourage you to use explicit package information.
In your MyTools.jar there should be a package with the name MyTools. And before compiling you should add the jar to the classpath.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With