简体   繁体   中英

What exactly are class loaders in Java?

When a client says "Code should not have custom classloaders" in Java, what does that exactly mean? What can't I do?

A class loader is an object in Java responsible for finding binary representations of Java classes and loading them into the JVM. All JVMs begin with a boot class loader responsible for loading the user's initial class, along with some of the built-in types like Class and SecurityManager , but users can provide their own class loaders to find classes from other sources. For example, a custom class loader could generate its own classes by composing its own bytecode, or it could find classes from a networked source.

To comply with what your client is asking, you should not define your own class loader and should rely on the boot class loader to find all your classes. This is almost universally what's done in simple Java programs because the use cases for custom boot loaders are usually fairly complex and nuanced. You shouldn't need to worry about this restriction unless you specifically want to change the way that that JVM finds and loads classes.

Custom class loaders are usually used to dynamically generate code or to enhance existing classes.

For example some ORM implementations (JDO) use this to create code that handles translating Java objects to database tables. Other use is in transparent-clustering solutions (like Terracota) where objects are enhanced so that they automatically replicate themselves across the cluster.

This basically prevents you to dynamically generate and inject code into an existing application.

A class loader is an object that is responsible for loading classes. Whenever you instantiate a class using new the runtime system attempts load the class using one or more instances of the ClassLoader abstract class. You can define custom class loaders to load classes from the network, databases, other processes, or any conceivable data source.

So, if your client does not want you to use custom class loaders then be sure to never write a class that extends ClassLoader or any of it's derivatives. Please see the ClassLoader java API docs for more details.

A custom classloader would let you load classes from unconventional sources (from anywhere you can imagine, including out of nowhere, ie created on-the-fly). Since your client is saying giving that message, then classes can be loaded only from standard sources (eg filesystem, jar files, etc).

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