In Java, can we divide a class into multiple files

2019-03-22 10:34发布

Any possibility to divide a class into multiple physical files using Java?

标签: java class
7条回答
来,给爷笑一个
2楼-- · 2019-03-22 10:47

Using just javac, this is not possible. You could of course combine multiple files into a single .java file as part of your build process, and invoke javac afterwards, but that would be cumbersome on so many levels that it is unlikely to be useful.

Maybe you could explain your problem, then we can help better.

If you feel your .java files are too large, you should probably consider refactoring.

查看更多
一夜七次
3楼-- · 2019-03-22 10:48

No, the whole of a class has to be in a single file in Java.

If you're thinking of C#'s "partial types" feature, there's no equivalent in Java. (If you weren't thinking of C#, ignore this :)

查看更多
Lonely孤独者°
4楼-- · 2019-03-22 10:48

This might be a good idea if the class is really so large such that the implemented concepts are not easy to grasp. I see two different ways to do this:

  1. Use inheritance: Move general concepts of the class to a base class and derive a specialized class from it.

  2. Use aggregation: Move parts of your class to a separate class and establish a relationship to the second class using a reference.

As previously mentioned, there is no concept like partial classes in Java, so you really have to use these OOP mechanisms.

查看更多
Luminary・发光体
5楼-- · 2019-03-22 11:00

No you can't. If your class is too big than you should split it into two or more.

查看更多
乱世女痞
6楼-- · 2019-03-22 11:06

No, in Java this can not be done.

查看更多
Summer. ? 凉城
7楼-- · 2019-03-22 11:09

Of course it is possible, but I don't think it's useful at all.

To start off, divide isn't really the question I guess, you just compile the file and split it up whichever way you want.

Now to put them back together all you need to do is to write a custom class loader which loads all the pieces, combines them into a single byte array, then calls defineClass().

Like I said, it does look pretty pointless and is probably not what you want and definitely not what you need, but it is technically possible.

(I did something similar once as a joking way of obfuscating code: bytes of the class file were scattered in constants of all the other classes in the application. It was fun, I have to admit.)

查看更多
登录 后发表回答