Joseph Nields
Joseph Nields

Reputation: 5661

Java/IntelliJ keep classes in another folder but in the same package

Is there a way to keep your classes separated in different folders without keeping them in a different package?

I have a collection of about 40 classes, and I do want all of them to be in the same package, but I want a way to visually group them so it's a bit easier to navigate as this grows in size.

Is there a way to do this with IntelliJ? In Java in general?

The reason I don't want sub-packages is as follows:

Foo in package Foo:

package Foo;
public class Foo {
    public static void main(String[] args) {
        Bar.FooBar(); //<--compile error
    }
}

and Bar in package Foo.Bar:

package Foo.Bar;

public class Bar {
    static void FooBar() {}
}

Upvotes: 4

Views: 4599

Answers (3)

Joe Almore
Joe Almore

Reputation: 4329

If you use maven in IntelliJ, you could use the build-helper-maven-plugin in your build section of your pom file like this:

<build>
   <plugins>
       <plugin>
         <groupId>org.codehaus.mojo</groupId>
         <artifactId>build-helper-maven-plugin</artifactId>
         <version>1.9.1</version>
         <executions>
            <execution>
               <id>src</id>
               <phase>generate-sources</phase>
               <goals>
                  <goal>add-source</goal>
               </goals>
               <configuration>
                  <sources>
                     <source>../your/additional/source/path</source>
                  </sources>
               </configuration>
            </execution>
         </executions>
      </plugin>
   </plugins>
</build>

This way you can separate your code into multiple logical folders while using the same package in the project, and maven will take care of grouping them all together when you run any maven command.

Upvotes: 1

Hypino
Hypino

Reputation: 1248

If you have more than one source classpath with the same package structure, you can do this.

In IntelliJ, you can simply make a new folder and then mark that folder as a Source folder. (Right Click folder -> Mark Directory As -> Sources Root). Again, as long as the package structure is the same, all classes in the same packages will end up together.

Upvotes: 5

cjstehno
cjstehno

Reputation: 13994

You could do this with Favorites in IntelliJ. They would be grouped visually, but would remain in the same package folder; however, not suggesting this as being a good design approach.

Upvotes: 0

Related Questions