Difference between the execution of java -cp and the implementation of a class loader

微信扫一扫,分享到朋友圈

Difference between the execution of java -cp and the implementation of a class loader

I would like to know whether there’s any functional difference between running my Java app with the -cp command line switch (supplying a folder or a list of jars), and implementing a class loader (for example, using the URLClassLoader class) to load classes.

Example code:

// -cp approach
java -jar  -cp ~/folder/with/jars

The other approach:

// URLClassLoader approach. urls is an array that points to the .jars under ~/folder/with/jars
URLClassLoader loader = new URLClassLoader(urls);
loader.findClass(...);

Well, for one, using a class loader as in your example would mean hardcoding paths in the source, unlike with -cp
.

Plus you’d be in charge of loading the classes yourself instead of letting the jvm resolve them. Looks like a lot of unnecessary extra code to me unless there’s a good reason to do that.

Another difference (and advantage of a class loader) is being able to load them on demand.

微信扫一扫,分享到朋友圈

Difference between the execution of java -cp and the implementation of a class loader

DBS launches real-time cross-border payment tracking for all corporate and SME clients

上一篇

Square to buy website builder Weebly

下一篇

你也可能喜欢

Difference between the execution of java -cp and the implementation of a class loader

长按储存图像,分享给朋友