Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java code to import JAR file

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.

like image 275
KTF Avatar asked Feb 14 '26 08:02

KTF


2 Answers

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 and ThirdClass.class, all of which are in package org.somepackage.

Given the above, you would add

import org.somepackage.FirstClass

at the top of a source file to import the class called FirstClass.

like image 156
The Head Rush Avatar answered Feb 15 '26 22:02

The Head Rush


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/*

like image 31
ControlAltDel Avatar answered Feb 16 '26 00:02

ControlAltDel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!