How to create the default java module programatically ?

I've successfully created a project and opened it on the IntelliJ editor 

val projectManager = ProjectManager.getInstance()
val project = projectManager.loadAndOpenProject("/Users/X/Work/TestProject")

But since the module was not created as default, I want to do the following things. 

  1. Create a module (I have folderPath as a String)
  2. detect and add source, test and resource folder automatically
  3. add jar folder dependencies to the module (I would have folderPath as String array)
0
6 comments

Let mi just quickly clarify one thing - you want to create a new module from scratch as using UI but programmatically?

Or create a new module by importing the sources from the existing directory?

0

Yes, you are right. I want to create a module programatically. It's just too difficult to find the right methods that the UI uses. 

0

Self answering: 

1. To create a project for any given folder 

val projectManager = ProjectManager.getInstance();
val project = projectManager.loadAndOpenProject(projectLocation)

2. To create a module inside that project

val moduleManager = ModuleManager.getInstance(project)
val module = moduleManager.newModule(projectLocation + File.separator + projectName + ".iml", "JAVA_MODULE")

3. You cannot detect sources automatically. To add source and test files

val moduleRootManager = ModuleRootManager.getInstance(module)
val modifiableRootModel = moduleRootManager.modifiableModel
val localFileSystem = LocalFileSystem.getInstance()
val contentEntry = modifiableRootModel.addContentEntry(localFileSystem.findFileByIoFile(projectLocation))
contentEntry.addSourceFolder(localFileSystem.findFileByIoFile(File(projectLocation + File.separator + "src" + File.separator + "main"))!!, false)
modifiableRootModel.commit()

Please help me figure out how do I add Jar folders / dependencies. I was able to figure out that we need to use

modifiableRootModel.addOrderEntry()

But unable to find what to pass if I want to add a JAR folder or another module as a dependency. 

0

Still waiting for an answer for this 

Please help me figure out how do I add Jar folders / dependencies. I was able to figure out that we need to use

modifiableRootModel.addOrderEntry()

But unable to find what to pass if I want to add a JAR folder or another module as a dependency. 

0

To add another module as a dependency, use ModuleRootModificationUtil.addDependency(@NotNull Module from, @NotNull Module to)

To add .jar file as a dependency: ModuleRootModificationUtil.addModuleLibrary(@NotNull Module module, @NotNull String classesRootUrl)

In general, you should review this ModuleRootModificationUtil utils class.

0

Abhaydoshi7 Jakub Chrzanowski
So basically I am trying to do kind of the same thing. I want to create a module inside a module but I am unable to get

projectLocation

It will be so kind if you can provide a full example.

0

Please sign in to leave a comment.