缺少依赖项时的对象实例化 (Java)
伙计们,谁能解释一下以下场景:
1) Web 应用程序的 lib
目录中有 module1.jar
。该模块中有一个类 A
:
package module1;
import module2.B;
public interface IA {
void methodOk() {}
void methodWithB(B param) {}
}
package module1;
import module2.B;
public class A implements IA {
public A() {}
//...
void methodWithB(B param) {
//do job on B
}
}
2) module2.jar
不存在 - 它不在类路径中。
3) 应用程序能够创建A
类的对象,尽管它缺少依赖项。在应用程序中调用方法A.methodOk()。
如果您能提供有关此方面的任何规范的参考,那就太好了。 多谢。
Guys, can anyone explain the following scenario:
1) Web application has module1.jar
in its lib
directory. There is a class A
in that module:
package module1;
import module2.B;
public interface IA {
void methodOk() {}
void methodWithB(B param) {}
}
package module1;
import module2.B;
public class A implements IA {
public A() {}
//...
void methodWithB(B param) {
//do job on B
}
}
2) module2.jar
is absent - it is not in the classpath.
3) Application is able to create objects of class A
though it's missing the dependency. In application a method A.methodOk() is called.
Would be cool if you could give a reference to any spec on this.
Thanks a lot.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于代码已经编译过了,所以除非直接使用类
B
,否则不会抛出错误。从代码的外观来看,您实际上并未将B
实例用于任何用途。Since the code is already compiled, it will not throw an error until you directly use class
B
. From the looks of your code, you don't actually use an instance ofB
for anything.如果 B 在任何地方都没有被 A 使用,那么生成的字节码将不会引用 module2.B,因此它会被编译掉。不存在依赖关系,除了在本例中的编译时。
如果问题不清楚并且 B 在 A 中的某处使用,那么我有兴趣查看更多代码来尝试确定发生了什么。
If B is not used by A anywhere, then the resulting bytecode will have no reference to module2.B, therefore it gets compiled away. No dependency exists, except at compilation in this case.
If the question is unclear and B is used in A somewhere, then I'd be interested in seeing more code to try to determine what's going on.
从类加载器的角度来看。如果您从不需要加载该类,那么您并不关心该类的字节码是否丢失。
你的问题实际上是“什么触发了类加载?”
我能立即想到的两个原因是:
- 建造
- 静态访问
Look at it from the perspective of the classloader. If you never have to load the class, you don't care if the bytecode for that class is missing.
Your question is really, "What triggers classloading?"
Two reasons I can think of off the top of my head are:
- Construction
- Static access