In Java, can we divide a class into multiple files

2019-03-22 10:43发布

问题:

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

回答1:

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 :)



回答2:

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.



回答3:

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.



回答4:

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.)



回答5:

No, in Java this can not be done.



回答6:

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



回答7:

Yes You Can!

For the sake of completion:

Since Java 8, you have the concept of default methods.

you can split up your class into multiple files/subclasses by gently abusing interfaces

observe:

MyClassPartA.java

interface MyClassPartA{
    public default int myMethodA(){return 1;}
}

MyClassPartB.java

interface MyClassPartB{
    public default String myMethodB(){return "B";}
}

and combine them:

MyClass.java

public class MyClass implements MyClassPartA, MyClassPartB{}

and use them:

MyClass myClass = new MyClass();

System.out.println(myClass.myMethodA());
System.out.println(myClass.myMethodB());

You can even pass variables between classes/files with abstract getters and setters that you will need to realize/override in the main class, or a superclass of that however.



标签: java class