Class.forName()

There are Class objects (objects of class Class) that represent classes (including arrays), interfaces, and primitives. The Class.newInstance method lets you create new objects of that class without requiring a variable declared specifically of that class. You are using the default public no arg constructor. Your class had better have one. This allows code to be much more open ended than in other languages, with new variants added dynamically. The Class.getName method lets you display the class name. There are also methods to discover the details of the fields and methods associated with the class in the java.lang.reflect.* package.

Class.forName eagerly loads the class if it not already loaded. Inside the JVM there is a HashMap of all the classes that have been previously loaded. So Class. forName takes under a millisecond if the class you have want is already loaded, If not, it might take 15 milliseconds or so to load it. You pay this time penalty only the first time you use the class. Class. forName is still slower than hard coding the name of the class into your code. With hard coding, you avoid repeated HashMap lookups.



0 comments: