简体   繁体   中英

How Do I Place Auto-generated Java Classes in a Single .java File?

As everyone knows - public java classes must be placed in their own file named [ClassName].java

( When java class X required to be placed into a file named X.java? )

However, we are auto-generating 50+ java classes, and I'd like to put them all in the same file for our convenience. This would make it substantially easier to generate the file(s), and copy them around when we need to.

Is there any way I can get around this restriction? It seems like more of a stylistic concern - and something I might be able to disable with a compiler flag.

If not, what would you recommend?

Can you put wrapper class around your classes? Something like:

public class Wrapper {
   public static class A {...}
   public static class B {...}

....
}

Then you can access them via Wrapper.A , Wrapper.B .

At the .class level, this is a requirement per the Java spec. Even the inner classes get broken out into their own class file in the from Outer$Inner.class . I believe the same is true at the language level.

Your best bet is to generate the files and make your copy script smart. Perhaps generate them and zip them up. Usually, if you have to move these files around then either everyone has the same generator script OR you distribute them as a JAR.

Is there any way I can get around this restriction?

You can change your generated source code to make it acceptable; eg by using nested classes, by putting the generated classes into their own package.

It seems like more of a stylistic concern - and something I might be able to disable with a compiler flag.

It is not just a stylistic concern:

  • The one file per class rule is allowed by the Java Language Specification.
  • It is implemented by all mainstream Java compilers.
  • It is implemented by all mainstream JVMs in the form of the default classloader behavior.
  • It is assumed by 3rd party Java tools; eg IDEs, style checkers, bug checkers, code generation frameworks, etc.

In short, while it would theoretically be legal to implement a Java ecosystem that didn't have this restriction, it is impractical. No such compiler switch exists, and implementing one would be impractical for the reasons above.


The nested class solution is a good one. Another alternative would be to put the generated classes into a separate package (but with separate file) to make them easier to manage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM