質問

If I have a Java package, for example:

package org.foo.bar.stuff;

I can store the source .java files in a directory src/org/foo/bar/stuff, given that I add src/ to my classpath. In this example the directory contents tree is like this:

`-- src
    `-- org
        `-- foo
            `-- bar
                `-- stuff
                    |-- ICat.java
                    `-- IMouse.java

If I could define a "base" package name, eg. org.foo.bar for a directory like /stuff, the tree could become like this:

`-- src
    `-- stuff  # has defined base "org.foo.bar"
        |-- ICat.java
        `-- IMouse.java

Is there technically a way to define a "base" package name, ie. org.foo.bar, for a directory like /stuff, in order to avoid nested directories?

役に立ちましたか?

解決

While the Java specification doesn't enforce it, all well-known compilers use directory structures. The specification explicitly states a database for storage of classes, which wouldn't use any directories at all.

Short answer: If you're using standard Java tools, you can't avoid nested directories.

7.2. Host Support for Packages

Each host system determines how packages and compilation units are created and stored.

...

In simple implementations of the Java SE platform, packages and compilation units may be stored in a local file system. Other implementations may store them using a distributed file system or some form of database.

If a host system stores packages and compilation units in a database, then the database must not impose the optional restrictions (§7.6) on compilation units permissible in file-based implementations.

...

Systems that use a database must, however, provide an option to convert a program to a form that obeys the restrictions, for purposes of export to file-based implementations.

(It sounds like you're working around the real problem.)

他のヒント

While it is possible to do this, I do not necessarily endorse it. If (for some reason) you don't want to nest your classes into packages, you could nest your classes in your classes (if you really want)...

package it.is.a;

public class Demo {
  public static class A {}
  public static class B {}
}

Then it.is.a.Demo.A and it.is.a.Demo.B are grouped with Demo.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top