Sharing Java packages between modules in IntelliJ?

2019-03-26 01:48发布

问题:

I'm trying to figure out how can I share packages between two modules in a single IntelliJ project, and I can't seem to find the right way to do it. I know it can be done in Eclipse, but I'm not very well-versed with it. In a nutshell, I'm trying to reproduce the same kind of project environment created by AppEngine-connected Android projects.

Here's the "problem" as best I can lay it out

Project A.

  • Module 1; AppEngine + GWT + whatever else
  • Module 2; Android

Each module has its own source directory within the Project's main directory:

  • /ProjectA/Module1/src
  • /ProjectA/Module2/src

I create packages for both modules, and write the various classes needed for each. Most classes are unique to the module / platform, and are packaged into their own namespace

Module 1

  • com.example.myproject.server
  • com.example.myproject.server.domain
  • com.example.myproject.server.services
  • ...

Module 2

  • com.example.myproject.client
  • com.example.myproject.client.activities
  • com.example.myproject.client.fragments
  • ...

However, there are some identical Interfaces and Enums that I use within both modules: Now I'd like to have all my identical code in a single package shared between the two, so I don't have to copy the source between packages every time I change something around.

  • com.example.myproject.shared
  • com.example.myproject.shared.interfaces
  • ...

I know IntelliJ will allow you to configure multiple content Roots as part of a module's configuration. But it doesn't seem that two modules care share the same content root if their part of the same IntelliJ Project...? Is there a better way to configure my project? Or am I missing something..?

回答1:

You could move shared code into another module that has its own content root, say:

/ProjectA/Module3/src

and then add a module dependency on Module3 to both Module1 and Module2.