程序可以在编译期间依赖库而不是运行时吗? [英] Can a program depend on a library during compilation but not runtime?

查看:23
本文介绍了程序可以在编译期间依赖库而不是运行时吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我了解运行时和编译时之间的区别以及如何区分两者,但我只是认为没有必要区分编译时和运行时依赖项.

I understand the difference between runtime and compile-time and how to differentiate between the two, but I just don't see the need to make a distinction between compile-time and runtime dependencies.

让我感到窒息的是:程序如何不依赖在运行时依赖于它在编译期间依赖的东西?如果我的 Java 应用程序使用 log4j,那么它需要 log4j.jar 文件才能编译(我的代码与 log4j 内部的成员方法集成和调用成员方法)以及运行时(我的代码完全无法控制 log4j 中的代码发生后会发生什么.jar 已运行).

What I'm choking on is this: how can a program not depend on something at runtime that it depended on during compilation? If my Java app uses log4j, then it needs the log4j.jar file in order to compile (my code integrating with and invoking member methods from inside log4j) as well as runtime (my code has absolutely no control over what happens once code inside log4j.jar is ran).

我正在阅读 Ivy 和 Maven 等依赖项解析工具,这些工具明确区分了这两种类型的依赖项.我只是不明白它的必要性.

I'm reading up on dependency resolution tools such as Ivy and Maven, and these tools clearly make the distinction between these two types of dependencies. I just don't understand the need for it.

谁能给出一个简单的,国王的英语"式的解释,最好是一个即使像我这样的可怜的sap也能理解的实际例子?

Can anyone give a simple, "King's English"-type explanation, preferably with an actual example that even a poor sap like me could understand?

推荐答案

通常在运行时需要编译时依赖项.在 maven 中,compile 作用域依赖项将在运行时添加到类路径中(例如,在 wars 中,它们将被复制到 WEB-INF/lib).

A compile-time dependency is generally required at runtime. In maven, a compile scoped dependency will be added to the classpath on runtime (e.g. in wars they will be copied to WEB-INF/lib).

然而,这不是严格要求的;例如,我们可能针对某个 API 进行编译,使其成为编译时依赖项,但随后在运行时包含一个也包含该 API 的实现.

It is not, however, strictly required; for instance, we may compile against a certain API, making it a compile-time dependency, but then at runtime include an implementation that also includes the API.

可能有一些边缘情况,项目需要一定的依赖才能编译,但实际上不需要相应的代码,但这种情况很少见.

There may be fringe cases where the project requires a certain dependency to compile but then the corresponding code is not actually needed, but these will be rare.

另一方面,包含在编译时不需要的运行时依赖项是很常见的.例如,如果您正在编写 Java EE 6 应用程序,您将针对 Java EE 6 API 进行编译,但在运行时,可以使用任何 Java EE 容器;正是这个容器提供了实现.

On the other hand, including runtime dependencies that are not needed at compile-time is very common. For instance, if you're writing a Java EE 6 application, you compile against the Java EE 6 API, but at runtime, any Java EE container can be used; it's this container that provides the implementation.

使用反射可以避免编译时依赖.例如,可以使用 Class.forName 和实际加载的类可以通过配置文件进行配置.

Compile-time dependencies can be avoided by using reflection. For instance, a JDBC driver can be loaded with a Class.forName and the actual class loaded be configurable through a configuration file.

这篇关于程序可以在编译期间依赖库而不是运行时吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆