简体   繁体   中英

Java class loading from Jar file

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM