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

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

问题描述

我理解运行时和编译时之间的区别以及如何区分这两者,但我不认为需要区分编译时和运行时依赖。 / p>

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



我正在阅读依赖解析工具,例如Ivy和Maven,这些工具显然区分了这两种类型的依赖关系。我只是不明白它的必要性。



任何人都可以给出一个简单的King's English型解释,最好还有一个实际的例子,即使是一个糟糕的汁液像我这样理解?

解决方案

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



但并非严格要求;例如,我们可以针对某个API进行编译,使其成为编译时依赖项,但是在运行时包含一个也包含API的实现。



可能存在边缘情况,项目需要一定的依赖项来编译,但实际上并不需要相应的代码,但这些很少见。



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



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


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.

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

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.

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

解决方案

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

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.

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.

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天全站免登陆