Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

A Thinking in Java program is as follows:

package typeinfo;
import static util.Print.*;

class Candy {
 static { print("Loading Candy"); }
}

class Gum {
 static { print("Loading Gum"); }
}

class Cookie {
 static { print("Loading Cookie"); }
}

public class SweetShop {
 public static void main(String[] args) {  
   print("inside main");
   new Candy();
   print("After creating Candy");
   try {
     Class.forName("Gum");
   } catch(ClassNotFoundException e) {
     print("Couldn't find Gum");
   }
   print("After Class.forName("Gum")");
   new Cookie();
   print("After creating Cookie");
 }
} 

I am expecting the output as follows:

/* Output:
inside main
Loading Candy
After creating Candy
Loading Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie
*/

But get

inside main
Loading Candy
After creating Candy
Couldn't find Gum
After Class.forName("Gum")
Loading Cookie
After creating Cookie

Obviously the try block is throwing a ClassNotFoundException, which is unexpected. Any ideas why the code throws this instead of initializing the Gum class, as expected?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

Your classes are in the package typeinfo, so their fully-qualified names are typeinfo.Gum, typeinfo.Candy and typeinfo.Cookie. Class.forName() only accepts fully-qualified names:

Parameters:

className - the fully qualified name of the desired class.

Change your code to:

try {
  Class.forName("typeinfo.Gum");
} catch(ClassNotFoundException e) {
  print("Couldn't find Gum");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...