"Static import" Mechanism

Source: Internet
Author: User
The "static import" mechanism is introduced in j2se 1.5. With this mechanism, you can use static members by skipping the class or interface name. This article describes how to use this mechanism and the precautions during use.

In Java programs, independent functions and constants are not allowed to be defined (of course, to be precise, only variables modified by final and assigned only once. Even from the perspective of their own functions, you do not need to attach anything to them. You also need to find a class or interface as the affiliated unit (in the class, you can attach various Members, in the interface, only constants can be attached ).

You can add static modifiers to them to define them as static members of this class or interface. A typical example of this is the java. Lang. Math class, which contains a large number of "functions" such as sin, cos, and "constants" such as PI and E ".

Traditionally, when accessing these affiliated functions, variables, and constants, you must add the names of affiliated units in front of them. If you only access these items occasionally, this method can work well. However, if you want to access these members frequently, this method is quite cool.

The "static import" mechanism is introduced in j2se 1.5. With this mechanism, you can use static members by skipping the class or interface name.

"Static import" or "static member import"

The static import mechanism is often directly translated into "static import ". However, in terms of meaning, "static member import" is a more appropriate translation method. However, considering the short description of "static import", it is estimated that there will still be powerful vitality.

Only constant-defined interfaces are included.

There is a work und to save the affiliated units before constants: define all constants in one interface, then let the classes that need these constants implement this interface (such an interface has a special name called "constant interface ").

This method can work. However, in this way, we can infer from "which interface is implemented by a class" "What constants are required for this class", which may expose implementation details.

1. Exact import Method

The exact method for importing a static member is to add a declaration similar to this to the beginning of the source file (before the definition of any class or interface:
Import static package name. Class or interface name. static member name;

Note that although this mechanism is called "static import", the order here is the opposite "Import static ". Once imported, you can directly access the source file by using the name of the member.

Listing 1: Import sin and PI using the exact import method // import math. Sin and math. Pi accurately
Import static java. Lang. Math. sin;
Import static java. Lang. Math. Pi;

Public class staticimportsamplea {
Public static void main (string [] ARGs ){
System. Out. println (sin (PI/2); // output "1.0"
}
} Special issues with classes and interfaces outside the package

The Java language does not require that each class and interface belong to a certain package. However, after j2se 1.4, both the Import Statement and the import static statement must be given the package name. In other words, for classes and interfaces that do not belong to any package, neither import itself nor static members of the package can be imported using import static.

2. On-demand import

The static import mechanism also supports an import method that does not need to specify the names of static members one by one. In this case, the following syntax should be used:

Import static package name. Class or interface name .*;

Note that this method only indicates that you can search for unknown members in this class or interface, rather than importing all static members in this class or interface.

Listing 2: Use the on-demand import method to import sin and PI // declaration to Java. Lang. Math for unknown members
Import static java. Lang. Math .*;

Public class staticimportsampleb {
Public static void main (string [] ARGs ){
System. Out. println (sin (PI/2); // output "1.0"
}
} 3. Various items that can be imported

Using the import static statement, you can import all the things modified by static in a class, including variables, constants, methods, and internal classes.

Listing 3: You can import package com. example. P3 to variables, constants, methods, and internal classes;

Public class staticimportee {
Public static int one = 1;
Public static final int two = 2;
Public static int three (){
Return 3;
}
Public static Class Four {
Public int value (){
Return 4;
}
}
} Package com. example. P3;
Import static com. example. p3.staticimportee .*;

Public class staticimporter {
Public static void main (string [] ARGs ){
System. Out. println (one );
System. Out. println (two );
System. Out. println (three ());
System. Out. println (New Four ());
}
} Unaffected Access Control

Static import cannot break through the limitations of the original access control mechanism in Java, but it does not add new restrictions in this regard. Previously, all static members with access permissions can be imported and used. However, static members without access permissions are still inaccessible after this method is used.

4. Conflicts between imports

Different classes (interfaces) can include static members with the same name. Therefore, during static import, "two statements import static members with the same name" may occur.

In this case, j2se 1.5 will handle the problem as follows:

  • If both statements are accurate or on-demand, compilation errors may occur.
  • If a statement adopts the exact import mode and the on-demand import mode, the exact import mode is effective.

NOTE: If two static members with the same name are attributes and the other is methods, there will be no conflicts because of the differences in the writing method during use.

Listing 4: a valid package com. example. P4 in the form of precise import;
Import static com. example. p4.importee1. Name;
Import static com. example. p4.importee1 .*;
Import static com. example. p4.importee2 .*;
Import static com. example. p4.importee2. pass;

Public class importer {
Public static void main (string [] ARGs ){
System. Out. println (name); // output "name1"
System. Out. println (PASS); // output "pass2"
}
} Package com. example. P4;

Public class importee1 {
Public static string name = "name1 ";
Public static string pass = "pass1 ";
} Package com. example. P4;

Public class importee2 {
Public static string name = "name2 ";
Public static string pass = "pass2 ";
} 5. local and external competition

Sometimes, the imported content may conflict with the local content. In this case, the processing rule is "local priority ".

Listing 5: The local package takes precedence over the external package com. example. P5;
Import static com. example. Zero .*;

Public class one {
Public static int flag = 1;
Public static void main (string [] ARGs ){
System. Out. println (FLAG); // output "1"
}
} Package com. example. P5;

Public class zero {
Public static int flag = 0;
} 6. Negative Impact of static Import

During compilation, all the names simplified due to the existence of static import will be decompressed back to the prototype by the compiler. Therefore, static import has no impact on performance. However, simplified names may cause maintenance problems.

Removing the type name before a static member helps to make the call more concise, but also loses the prompt about "where to define this thing, it makes reading comprehension more difficult. If the import source is very famous (such as Java. lang. math), or the total number of sources is relatively small, this problem is not serious; however, this is not a basic problem that can be ignored in the case of not both.

7. Summary

With the static import mechanism provided in j2se 1.5, you can use a simpler method to access the static members of callback classes and interfaces. However, the use of this mechanism is not costly, and improper use may cause some troubles to the maintenance work. Therefore, we need to make two trade-offs before specific use.

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.