0

I'm trying to understand how is it possible to have a runtime-only dependency in Java. I understand the concept of compile-time-only dependencies, for example when your code uses an Annotation library, and the annotations are consumed by the compiler to enforce some policies, but this library isn't used on runtime.

But regarding runtime-only dependencies, I can't understand how is possible.

Let's say my code contains Class A:

class A {
    void someMethod() {
        B b = new B();
        b.foo();
    {
}

So my code depends on class B, which is obviously a compile-time and runtime dependency. A runtime-only dependency implies that the dependency is not needed at compile time, which implies that my code doesn't directly refer to it, so why is it a dependency at all?

Would love some concrete example.

YoavKlein
  • 2,005
  • 9
  • 38
  • This has already been asked and answered here: https://stackoverflow.com/questions/45842742/when-would-i-need-maven-dependency-with-runtime-scope – vivek Aug 03 '23 at 09:30
  • Classic examples are 1) where your code runs inside a framework, 2) where you are implementing an application that supports plugins. (This is independent of how you express the "dependencies" ... and indeed the programming language.) – Stephen C Aug 03 '23 at 09:37
  • The common example are JDBC drivers: as long as you only use the interfaces and classes from the JDBC API, you don't need to driver at compile time, you only need it at runtime. – Mark Rotteveel Aug 03 '23 at 12:23

1 Answers1

0

If your code depends on an interface (or base class), it can be compiled. At runtime a concise implementation of the interface, or a subclass may be used, and these may come from additional jars that were not required during compile time.

You (or any library/framework used at runtime) can dynamically load classes via the Reflection API.

See https://docs.oracle.com/javase/tutorial/reflect/

Queeg
  • 7,748
  • 1
  • 16
  • 42
  • in this case, no particular implementation is a runtime dependency which I can declare of. There's only a compile-time dependency for the interface. What am I missing? – YoavKlein Aug 03 '23 at 10:55
  • You nailed it. Nothing you can declare of at compile time other than the interface. – Queeg Aug 03 '23 at 23:17
  • Build tools such as Maven and Gradle allows you to declare "runtime dependencies", and that is the question - what is the meaning of a runtime-only dependency? – YoavKlein Aug 04 '23 at 06:02
  • Many projects allow you to run the project through maven. Just invoke `mvn run`. Now how would you setup the runtime dependencies (the classpath) without such a feature? https://stackoverflow.com/questions/1089285/maven-run-project – Queeg Aug 04 '23 at 13:12