java编译时跳过依赖,程序可以在编译期间依赖于库而不是运行时吗?

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值