syzztem
syzztem

Reputation: 92

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.

Upvotes: 0

Views: 1362

Answers (1)

Andreas
Andreas

Reputation: 159086

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, i.e. 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 e.g. 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.

Upvotes: 4

Related Questions