How to use jar files without package information?

I have a can called "MyTools". The box is located in the 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 MyTools.jar in my UseTools.java. I tried this, but it does not 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 received 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 specify a package name in any class.

Do I need to set the package name in my jar classes?

+4
source share
3 answers

To mention something more related to the title of the question: In Java, you cannot access the classes in the default package from the code in the named package.

This means that if the classes in your jar file do not belong explicitly to any package, and inside the jar your files are located directly in the root folder without subfolders, they are in the default package. It is not very detailed and does not have modularity, as well as extensibility, but technically in order. Then you can use these classes only from code, which is also in the default package. But this does not necessarily mean that it must be in the same bank. If you have multiple src or class folders, they may contain classes in the default package that can interact. The organization in the JAR files and the package structure in your project are independent of each other.

However, I strongly recommend that you use explicit package information.

+3
source

MyTools.jar should have a package named MyTools. Before compiling, you must add jar to the classpath.

+1
source

You need to add -cp file.jar instead of -cp.

The latter will only receive .class files. By the way: why not use an IDE like netbeans, eclipse or intelliJ?

0
source

Source: https://habr.com/ru/post/1302146/


All Articles