Reputation: 89613
I'm fairly confused about the Class.forName in java. how do we explain what Class.forName is from a C# perspective?
use case: java.lang.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Upvotes: 0
Views: 476
Reputation: 25140
Class.forName returns an instance of a Class object. Class is equivalent to the c# class object.
Class.forName forces classes to load, if they have not already been loaded. As part of the class loading process is invoking any static blocks defined in the class. A static block looks like,
class Foo {
static {
System.out.println("loaded Foo");
}
}
//running this will print "loaded Foo"
Class.forName("Foo");
Static blocks are invoked only once, the first time a class is loaded, so repeatedly calling Class.forName("Foo") will only cause "loaded Foo" to be printed once. Creating a new instance of Foo will also cause the class to be loaded, if it has not already been loaded.
Generally, JDBC drivers will register themselves by calling DriverManager.registerDriver() in a static block, which is why calling Class.forName() loads the driver.
Upvotes: 3
Reputation: 240
You can use java.lang.Class.forName, when you want to instantiate an object in Java by simply giving objects name as a String.
Its similar to using Activator.CreateInstance(objectType) in c#.
For more info, read http://java.sun.com/developer/technicalArticles/ALT/Reflection/ and http://msdn.microsoft.com/en-us/library/d49ss92b(v=VS.71).aspx
Upvotes: 1