Simon Morgan
Simon Morgan

Reputation: 2248

How do I use classes from another project in IntelliJ IDEA?

I have two IntelliJ IDEA Java projects; ProjectA and ProjectB. I want to import and use code from ProjectA in ProjectB. How do I do this?

In Eclipse I would simply go to ProjectB's Build Path settings and add ProjectA.

Upvotes: 32

Views: 68609

Answers (4)

Natalija
Natalija

Reputation: 41

With Gradle: if you only manually add the dependency, you will get javaCompile task errors when building the project. You need to add the dependency in your build.gradle and load Gradle changes. In your build.gradle:

dependencies {
    implementation project(':<name_of_project>')
}

Upvotes: 0

user4948585
user4948585

Reputation:

You can create dependency between these projects (Make project B dependent on project A) What it does is essentially compiles project A first then put its compiled jar as dependency to Project B for compiling or running. You can do this manually also.

Steps in IDEA ( You won't need these below steps if you follow below mentioned best practices):

  1. Right click on project and select open module settings
  2. Go to dependencies tab
  3. click plus sign and add the module you want to use.

Best practices:

  1. Never use project class in another project, always create a nice interface and use that interface in other projects.
  2. If possible use Dependency Injection to manage different projects and their dependencies (this internally uses interfaces to do this)
  3. Use build tool like ant/maven/ivy etc to manage build process.
  4. Enjoy :)

Upvotes: 29

Ivaylo D. Ivanov
Ivaylo D. Ivanov

Reputation: 3859

Eclipse's concepts of "workspace" and "project" are matched by IntelliJ IDEA's "project" and "module". So one way of doing this is to create a project, say ProjectAB, and import your two existing ProjectA and ProjectB as modules, I'll call them ModuleA and ModuleB.

Right after that make sure that in the project tree both modules have correct folders marked as "source" folders (in my case they are ModuleA/src/main/java and ModuleB/src/main/java).

Then you have to configure ModuleB to depend on ModuleA (ModuleB > Dependencies> Add > Module Dependency).

Upvotes: 7

Paul
Paul

Reputation: 179

you have to create a module of your Project A and add in the path of your project B.

Follow this link for learn how to create module and use it in other project : Creating a module library

Hope i help you

EDIT : ok so you have to create a module or a package with your Project A a .jar.

after do this, go to File -> project structure.

On this windows go to Librairies -> click on + and select your module project B.jar.

and Now you have to import your librairie in your class like
import projectb.*;

now instancie the class you want to use and you can use all of the method of this class

hope i help you with that precision

Upvotes: 1

Related Questions