Reputation: 4517
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");
Upvotes: 3
Views: 350
Reputation: 718678
Your question doesn't make a lot of sense as written. Class.forName
and Class.getResourceAsStream
are doing different things. They are interchangeable.
The only way to compare them would be if you were comparing loading a class full of (say) static
fields initialized with data versus reading a resource containing the same data. If that is what you are talking better, the getResourceAsStream
approach is better in a number of respects:
If you are asking if you can use getResourceAsStream()
to load classes (in the normal sense), the answer is no. Sure you can get the bytecodes, but you have to do "other stuff" to turn those bytecodes into executable classes / methods in the JVM.
Upvotes: 0
Reputation: 1362
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.
Upvotes: 1