Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jar files without package information?

Tags:

java

jar

javac

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?

like image 235
vikasde Avatar asked Feb 23 '10 17:02

vikasde


People also ask

How can I view the contents of a JAR file without extracting it?

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.

How do I access files inside a jar?

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.


2 Answers

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.

like image 142
mkraemerx Avatar answered Sep 20 '22 23:09

mkraemerx


In your MyTools.jar there should be a package with the name MyTools. And before compiling you should add the jar to the classpath.

like image 20
GuruKulki Avatar answered Sep 23 '22 23:09

GuruKulki