The book says that this method can load classes, so I wrote the following program
Class Gum {
Static {System. out. print ("Loading Gum ");}
}
Public class SweetShop {
Public static void main (String args []) {
Try {
Class. forName ("Gum ");
} Catch (ClassNotFoundException e ){
System. out. print ("Couldn't find Gum ");
}
}
}
Program output: Couldn't find Gum
If this method can load classes, shouldn't static fields in the class be initialized?
I think the output should be:
Loading Gum Couldn't find Gum
Thank you for your answers.
Best Answer
I can't see your package, mainly the path in forName. I am right. I will give you my code!
Package test;
Class Gum {
Static {System. out. println ("Gum Class ");}
}
Public class TestDemo {
Public static void main (String [] args ){
// TODO Auto-generated method stub
Try {
Class. forName ("test. Gum ");
} Catch (ClassNotFoundException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
System. out. println ("Couldn't find Gum ");
}
}
}
Question
Why can't I do it without adding a package name? They are in the same directory. Isn't it enough to use a relative path?
Answer
If this parameter is not specified, the path of the file Gum. java is used by default. However, your name is Test. java! (Your name is SweetShop. java) in forName (), the parameter is the fully qualified name of the required class. Otherwise, the class cannot be located. You can see that the Class in JDK API1.6 should be helpful to you!