Class. forName () and package problems

Source: Internet
Author: User

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!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.