Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 846
Mike Flynn Avatar asked Feb 04 '11 23:02

Mike Flynn


2 Answers

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.

like image 71
templatetypedef Avatar answered Sep 22 '22 10:09

templatetypedef


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.

like image 31
Peter Knego Avatar answered Sep 22 '22 10:09

Peter Knego