java 编译时间,编译时间与运行时间依赖关系 - Java

What is the difference between compile time and run time dependencies in Java?

It is related to class path, but how do they differ?

解决方案

Compile-time dependency: You need the dependency in your CLASSPATH to compile your artifact. They are produced because you have some kind of "reference" to the dependency hardcoded in your code, such as calling new for some class, extending or implementing something (either directly or indirectly), or a method call using the direct reference.method() notation.

Run-time dependency: You need the dependency in your CLASSPATH to run your artifact. They are produced because you execute code that accesses the dependency (either in a hardcoded way or via reflection or whatever).

Although compile-time dependency usually implies run-time dependency, you can have a compile-time only dependency. This is based on the fact that Java only links class dependencies on first access to that class, so if you never access a particular class at run-time because a code path is never traversed, Java will ignore both the class and its dependencies.

Example of this

In C.java (generates C.class):

package dependencies;

public class C { }

In A.java (generates A.class):

package dependencies;

public class A {

public static class B {

public String toString() {

C c = new C();

return c.toString();

}

}

public static void main(String[] args) {

if (args.length > 0) {

B b = new B();

System.out.println(b.toString());

}

}

}

In this case, A has a compile-time dependency on C through B, but it will only have a run-time dependency on C if you pass some parameters when executing java dependencies.A, as the JVM will only try to solve B's dependency on C when it gets to execute B b = new B(). This feature allows you to provide at runtime only the dependencies of the classes that you use in your code paths, and ignore the dependencies of the rest of the classes in the artifact.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值