Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class.forName() versus direct class loading

Tags:

java

class

I found some code loading resources this way:

Class.forName(myClass.class.getName()).getResourceAsStream("myResource");

First, I wondered about the interest of using such a structure. It appears Class.forName("className") enables a dynamic loading, loading the class only when needed (this is the typical structure when loading a JDBC driver, for instance).

Yet, is not the dynamic loading inefficient in this case since the class is in code? Would there be any difference if I wrote the following?

myClass.class.getResourceAsStream("myResource");
like image 604
Chop Avatar asked Jun 08 '26 09:06

Chop


1 Answers

mmyClass.class.getResourceAsStream("myResource"); should be prefered option since it does not make search. Result is the same since myClass.class.getName() is used in forName, not just predefined string.

like image 143
popfalushi Avatar answered Jun 10 '26 08:06

popfalushi