Java类加载从Jar文件中

huangapple go评论63阅读模式
英文:

Java class loading from Jar file

问题

我有一个巨大的JAR文件,里面有好几个类,但是我的应用程序中的对象图只需要A类和B类(以及JVM所需的其他默认类)。如果是这样的情况,Java会将整个JAR文件加载到内存中吗?我的意思是,我是否应该创建另一个只包含A类和B类的JAR文件?我已经阅读了Java中的类加载机制,我猜Java只会加载所需的类以及默认类,但我不确定。感谢您的时间。

英文:

I have a huge jar file with several classes, but my object graph in my application require only two classes A and B (along with other default classes required by JVM). If that's the case, will Java load the whole Jar file into memory? I mean should I create another Jar file with only classes A and B? I have read the class loading mechanism in Java, and I guess Java will only load the required classes in addition to the default classes, but I am not sure. Thanks for your time.

答案1

得分: 1

Java会将整个Jar文件加载到内存吗?

如果您将那个.jar文件放在类路径上,是的,JVM将会将整个.jar加载到为该进程分配的内存中;

我的意思是,我是否应该创建另一个只包含A和B类的Jar文件?

似乎它目前尚未使用Project Jigsaw的JPMS,很可能最好将这两个类分别打包;

我已经阅读了Java中的类加载机制,我猜Java只会加载所需的类,除了默认的类,但我不太确定。

尽管.jar文件会被加载到内存中,但是如果在您的应用程序中根本没有使用这些类,Java将不会加载它们。

它们会在应用程序需要时加载

在类被使用/需要的那一刻,Java运行时环境会调用Java ClassLoader,并动态将类加载到内存中。

"类被需要/使用"指的是以下情况之一:

  • 类被实例化(创建了其对象);
  • 该类的静态成员(方法或字段)被访问/引用;
  • 类被反射访问;
  • 类已从命令行/Shell运行。
英文:

>will Java load the whole Jar file into memory?

If you put that .jar file on the class-path - yes, JVM will load entire .jar into memory allocated for the process;

>I mean should I create another Jar file with only classes A and B?

Seems like it does not (yet) use JPMS of Project Jigsaw, and most likely, it is better to package those two classes separately, yes;

>I have read the class loading mechanism in Java, and I guess Java will only load the required classes in addition to the default classes, but I am not sure.

Despite the fact, that .jar will be loaded into memory, Java will not load classes if they are NOT used, in your application, at all.

They are loaded when they are required by the application.

At the moment the class is used/required, the Java ClassLoader is called by the Java Runtime Environment and this(these) ClassLoader(s) load classes into memory dynamically.

Class is required/used, means anything from this:

  • Class is instantiated (its object is created);
  • Static member (method or field) of that class is accessed/referenced;
  • Class is accessed by reflection;
  • Class has been run from command line / shell.

huangapple
  • 本文由 发表于 2020年10月3日 00:04:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64174794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定