My understanding of Java's package and import mechanism (beginner's experience)

Source: Internet
Author: User
Tags continue net variables reference variable thread zip access
Beginners | experience
The following test conditions are on your machine, set the path command path= d:\jdk1.4\bin;d:\jdk1.4\lib, and you can perform the Java and Javac commands normally without setting the classpath path.







Talking about package and import mechanism from a simple example



Basic principles: Why Java files and class files need to be effectively placed under the relative path of the package to which they belong.



Why do you do it? If you are in a program, use the Package command package, and compile and execute the program directly. For example: Use the following procedure as an example:

Package A.B.C;

public class Hello

{

public static void Main (String args[])

{

System.out.println ("Hello the world!");

}

}

This program can be compiled, but when executed, it prompts the following error!

D:\my\xdj>javac Hello.java





D:\my\xdj>java Hello

Exception in thread "main" Java.lang.NoClassDefFoundError:hello (wrong name:a/

B/c/hello)

At Java.lang.ClassLoader.defineClass0 (Native method)

At Java.lang.ClassLoader.defineClass (classloader.java:537)

At Java.security.SecureClassLoader.defineClass (secureclassloader.java:12

3)

At Java.net.URLClassLoader.defineClass (urlclassloader.java:251)

At java.net.urlclassloader.access$100 (urlclassloader.java:55)

At Java.net.urlclassloader$1.run (urlclassloader.java:194)

At Java.security.AccessController.doPrivileged (Native method)

At Java.net.URLClassLoader.findClass (urlclassloader.java:187)

At Java.lang.ClassLoader.loadClass (classloader.java:289)

At Sun.misc.launcher$appclassloader.loadclass (launcher.java:274)

At Java.lang.ClassLoader.loadClass (classloader.java:235)

At Java.lang.ClassLoader.loadClassInternal (classloader.java:302)





D:\my\xdj>





In the XDJ directory to create a \a\b\c subdirectory put the Hello.java under it, for the command to compile and execute when the normal pass!





D:\my\xdj>javac D:\my\xdj\a\b\c\hello.java





D:\my\xdj>java A.b.c.hello

Hello the world!





D:\my\xdj>





Looking at the other case, let's create two files A.java and B.java files in the XDJ directory, as follows.

A.java File Contents:

Import a.b.c.*;

public Class A

{

public static void Main (string[] args)

{

b b1=new B ();

B1.print ();

}





}













A.java File Contents:

Package A.B.C;

public Class B

{

public void print ()

{

System.out.println ("I am the program output of the calling subclass!") ");

}

}





The following error is prompted when compiling the A.java file directly!





D:\my\xdj>javac A.java

A.java:1: Package A.B.C does not exist

Import a.b.c.*;

^

A.java:6: Cannot access B

Bad class file:. \b.java

File does not contain class B

Please remove or make sure it appears in the correct subdirectory of the Classpa

Th.

b b1=new B ();

^

2 errors





D:\my\xdj>

Next, we move the B.java to the xdj\a\b\c\, and remove the B.java from the \XDJ directory! Re-execute the compilation instructions, this time can be compiled successfully! You can see that B.java has been compiled at the same time, which is called Make compilation.





D:\my\xdj>javac A.java





D:\my\xdj>





Tip 1: If you still keep a B.java file in the \XDJ directory, you will still be able to make an error when executing the compiler command for the main program! You can try it yourself!

Tip 2: If you delete the \xdj\a\b\c\b.java file, keep the B.class file, execute the main program to compile the command can be passed, here you can not need the source code of the subroutine.





Ask a question: If the directory \a\b\c all to other directories, such as the D-Packing directory, in the \XDJ directory if the compile and execute commands?



Obviously, the following error will be reported! Of course, the prerequisite is that you do not set the classpath path, in fact, as long as the class search path is not set to my position will be wrong! You try it!





D:\my\xdj>javac A.java

A.java:1: Package A.B.C does not exist

Import a.b.c.*;

^

A.java:6: Cannot resolve symbol

Symbol:class b

Location:class A

b b1=new B ();

^

A.java:6: Cannot resolve symbol

Symbol:class b

Location:class A

b b1=new B ();

^

3 Errors





D:\my\xdj>java A

Exception in thread "main" java.lang.noclassdeffounderror:a/b/c/b

At A.main (a.java:6)





D:\my\xdj>

The solution can be compiled and executed normally with the following command:





D:\my\xdj>javac-classpath D:\ A.java





D:\my\xdj>java-classpath D:\;a

I am calling the subroutine output of the subclass!





D:\my\xdj>





Prompts the 3:-classpath parameter, which defaults to the current directory as the base, that is, without the-classpath parameter.

Tip 4: Using Java.exe or Javac.exe, it is best to explicitly specify the-classpath option, you can set the environment variable classpath, while setting the-classpath parameters and environment variables Classpath, will be based on the-classpath parameters. If you have a class with the same package name and class name in the path or jar file that they specify, it can cause confusion!





If you generate a packaged file A.zip in the root of D disk, and all files under its content directory a\b\c\, you can also compile and execute it with the following command.

D:\my\xdj>javac-classpath D:\a.zip A.java





D:\my\xdj>java-classpath D:\a.zip; A

I am calling the subroutine output of the subclass!





D:\my\xdj>





Let's pause for the above discussion! If you want to learn more about package and the import mechanism, you can continue to look down.





Deep analysis of package and import mechanism part



Whether you use the import directive or not, a class with the current directory will be given precedence by the compiler as long as it does not belong to any package. This is because the compiler always assumes that the class name you entered is the full name of the class (not part of any package), and then searches the path specified by-classpath for the. java file or. class file that belongs to the class, where you know that default Package's role is very special.

You must tell the compiler exactly which package class to use, or reference in the name of the package when you import it. When importing a package, be sure to specify the location of a package with the-classpath path. If you specify more than one path, if the package is found under one path, the package's class is referenced preferentially.

When the Java compiler starts compiling the source code for a class, it does one thing first, which is to create a "classpath reference table" that is based on parameter-classpath or CLASSPATH environment variables. If you do not specify an option-classpath or an environment variable classpath, by default the Classpath reference table has only one record, that is, the current directory ("."). The content of the environment variable classpath is covered by the option-classpath, and there is no cumulative effect.

When the compiler establishes the CLASSPATH reference table, the compiler then determines that it can use the data from the class reference tables as the relative starting path to find all the package used.

The compiler also completes a data structure named "Class reference table" and "Relative class reference table".

Part of the process associated with the import mechanism in the entire compiler is as follows: Package





Begin





Establishing a Class path reference table and a class reference table;

If successful: the Class name resolver:

If the class file for the class already exists, continue with the other compilation work.

If the file for the class does not exist, look for the source code file for the class:

If it is found, compile the

The source code of the class, continue

Other compile work.

At this point, you can return to the

Start, make mechanism,

Recursive compilation.

If not found, compile



End, issue a warning



Information.

If the build fails: the compilation finishes, a warning message (2) is issued.









Research on the nature of Java dynamic link



Whether you use several class declarations in the same source code (. java), they are all compiled into a. class file, even for internal classes and anonymous classes. In Java, it can be considered a dynamic link library for each class file that is composed of a class.

In the class file, all operations for the close-up class are converted to the full name of the class. Import has no function other than to direct the compiler to parse out the correct class name.

In the runtime, still use a compiler with the same program, that is, the establishment of the CLASSPATH reference table, and the use of dynamic link to load the class file mechanism flow is as follows:

Begin

Creates a class path reference table,

Based on the information inside the class file, the absolute path of the data composite class file that references the table to the classpath.

If the class file is found, check the class file internal information for the class, and conform to the relative path information:

Load the class if it is compliant.

If it does not meet, execute the error, issue

Exception information.

If the class file is not found, an error is executed and the exception message is sent.





Finally, it is useful to note that in Java, there are many classes of packages that are encapsulated in the Java language to complete functions such as input and output related to the bottom of the computer, commonly used data type conversions, and so on. If your program prompts you not to find such a base package, you can use the parameter-classpath or environment variable CLASSPATH to specify the location to solve such problems!

It's a little messy back there! I don't know if you can understand it! But I believe you will have some gains after reading my discussion of package and import. If you have any questions about package and import, you can discuss and communicate with me! My mail is: xiaodajin@sina.com.




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.