简体   繁体   中英

How to compile java classes independently

I'm currently wondering if you can compile Java class files without their dependencies, like.o files in C or C++. For example, I have a class A that has an instance of class B inside, but I only want to compile class A. Is there a way to do it? The point is to compile a java program using make because Gradle and Maven just won't let me do what I want to do.

Thank you.

Java is a statically typed language, like C/C++, so any class or method used by your class must be well-known, in order to compile your class.

In C/C++, we use header files to define classes and methods, without implementing them. That way we can compile classes that use them, using only the headers files, not the source files of the required classes/methods.

Java doesn't have header files, so the classes/methods must be available in full. They don't have to be available as source code, ie they can be pre-compiled and made available as .class files, most often packaged in .jar files.

So if you have class A depending on class B, you can compile B separately, then compile A separately, as long as B.class is on the classpath.

Unlike C/C++, the Java compiler can compile many files together, which is eg needed if A and B depends on each other (circular dependency).

If A and B are part of the same project, then compile them together. If A and B are part of different projects, build project B first, resulting in a B.jar file, then build project A, and give the jar file on the classpath when building project A.

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