Program compilation and code optimization-early (compile-time) optimization __JVM Learning Notes

Source: Internet
Author: User
Tags lowercase modifier uppercase letter
1: OverviewFront-End compilers: Sun Javac, incremental compiler (EJC) JIT compiler in Eclipse JDT: Hotspot vm c1,c2 compiler AOT compiler: GNC Compiler for the Java (GCJ), Excelsior JET

This chapter first introduces the first kind of front-end compiler, which is also approved by the compiler. 2:javac Compiler

Source code compiled from OpenJdk7, from the Sun Javac Source, the compilation can be roughly divided into 3 processes: parsing and filling the symbol table procedure Insert annotation processor annotation processing process. Parsing and bytecode generation process. 3:java syntax sugar Flavor 3.1: Generics and type erase

Java generics are typical syntactic sugars.

public static void Main (string[] args) {
        map<string, string> Map = new hashmap<string, string> ();
        Map.put ("Hello", "hi");
        Map.put ("How are You?", "Ate not." ");
        System.out.println (Map.get ("Hello"));
        System.out.println (Map.get ("How are"));
}

The result of compiling the above code is

public static void Main (string[] args) {
        map map = new HashMap ();
        Map.put ("Hello", "hi");
        Map.put ("How are You?", "Ate not." ");
        System.out.println ((String) map.get ("Hello"));
        System.out.println ((String) map.get ("How are");
}

Java generics are flawed in some scenarios, such as the following code that is not compiled

Import java.util.List;

public class Generictypes {public

    static void method (List<string> List) {
        System.out.println ("Invoke Method (List<string> List) ");
    }

    public static void Method (List<integer> list) {
        System.out.println (list<integer> list )");
    }
}

Then look at this code, this code adds a return value can be compiled successfully, provided that the trial JDK1.6 Javac compiler. This occurs because of the implementation of the method area of the virtual machine, which is allowed in the class file format as long as the descriptor is not exactly consistent.

Import java.util.ArrayList;
Import java.util.List;

public class Generictypes {public

    static String method (List<string> List) {
        System.out.println ("Invoke Method (List<string> List) ");
        Return "";
    }

    public static int method (List<integer> list) {
        System.out.println ("Invoke Method (List<integer> list)" );
        return 1;
    }

    public static void Main (string[] args) {method
        (new arraylist<string> ());
        Method (New Arraylist<integer> ());
    }

Java Virtual machines introduce new properties, such as signature, local variabletypetable, to address the problem of identifying parameter types that accompany generics. 3.2: Automatic boxing, unpacking and traversing cycle

The following code contains 5 syntactic sugars of generics, automatic boxing, automatic unboxing, traversal loops, and variable length parameters.

public static void Main (string[] args) {
        list<integer> List = arrays.aslist (1, 2, 3, 4);
        If there is another syntax sugar in JDK 1.7,
        //Can make the above code further abbreviated to List<integer> list = [1, 2, 3, 4];
        int sum = 0;
        for (int i:list) {
            sum = i;
        }
        SYSTEM.OUT.PRINTLN (sum);
    

The following code is compiled from the above code and gets

public static void Main (string[] args) {
        list list = Arrays.aslist (new integer[] {
                integer.valueof (1),
                Int Eger.valueof (2),
                integer.valueof (3),
                integer.valueof (4)});

        int sum = 0;
        for (Iterator Localiterator = List.iterator (); Localiterator.hasnext ();) {
            int i = ((Integer) Localiterator.next ()). Intvalue ();
            sum + = i;
        }
        SYSTEM.OUT.PRINTLN (sum);
    
3.3: Conditional compilation
public static void Main (string[] args) {
    if (true) {
        System.out.println (' Block 1 ');
    } else {
        System.out.println ("Block 2");
    }

The code above will be turned back into

public static void Main (string[] args) {
    System.out.println ("Block 1");

The following code compiler refuses to compile

public static void Main (string[] args) {
    //The compiler will prompt "unreachable code" while
    (false) {
        System.out.println ("");
    }
}

In addition to the syntax sugars mentioned above, Java has internal classes, enumeration classes, assertion statements, switch support for enumerations and strings (JDK1.7 support), definition and shutdown of resources (JDK1.7 support) in try statements, and so on. 3.4: The actual combat: Insert Annotation Processor 3.4.1: Actual target

     implements a code-checking tool similar to Checkstyle and Findbug. In order to achieve this effect, we need to set some writing specifications: Class (or interface): In accordance with camel-style nomenclature, first-letter capitalization method: In line with camel-style nomenclature, first-letter lowercase paragraph: class or instance variables (in accordance with camel-style naming, first-letter lowercase); Constants (required to be all made up of uppercase and underline, And the first letter cannot be underlined) 3.4.2: Code implementation

Import javax.annotation.processing.*;
Import javax.lang.model.SourceVersion;
Import javax.lang.model.element.Element;
Import javax.lang.model.element.TypeElement;

Import Java.util.Set; You can use "*" to support all annotations @SupportedAnnotationTypes ("*")//Only Java code @SupportedSourceVersion that supports JDK 1.6 ( 

    Sourceversion.release_6) public class Namecheckprocessor extends Abstractprocessor {private Namechecker namechecker; /** * Initialization name Check plugin/@Override public void init (Processingenvironment processingenv) {Super
        . Init (PROCESSINGENV);
    Namechecker = new Namechecker (processingenv); /** * The name check for each node of the input syntax tree/@Override public boolean process (SET&LT;? extends typeelement> A Nnotations, Roundenvironment roundenv) {if (!roundenv.processingover ()) {for (Element Element:roun
        Denv.getrootelements ()) namechecker.checknames (element);
    return false; }

}
Import Javax.annotation.processing.Messager;
Import javax.annotation.processing.ProcessingEnvironment;
Import javax.lang.model.element.*;

Import Javax.lang.model.util.ElementScanner6;

Import Java.util.EnumSet;
Import static javax.lang.model.element.elementkind.*;
Import static Javax.lang.model.element.Modifier.FINAL;
Import static Javax.lang.model.element.Modifier.PUBLIC;
Import static Javax.lang.model.element.Modifier.STATIC;

Import static Javax.tools.Diagnostic.Kind.WARNING;  /** * Program name Specification compiler plug-in:<br> * If the program naming is not specification, will output a compiler warning information * * public class Namechecker {private Final Messager

    Messager;

    Namecheckscanner Namecheckscanner = new Namecheckscanner ();
    Namechecker (processingenvironment processsingenv) {This.messager = Processsingenv.getmessager (); /** * To check the naming of Java programs, according to the requirements of section 6.8 of the Java language Specification, the Java program naming should conform to the following format: * * <ul> * <li> class or interface: Character
     Camel-style nomenclature, first letter capitalized.
     * <li> method: In accordance with camel-style nomenclature, the first letter lowercase. * <li> Field: *;ul> * <li> class, instance variables: In line with camel-style nomenclature, first letter lowercase.
     * <li> constants: All caps are required. * </ul> * </ul>/public void CheckNames (element Element) {Namecheckscanner.scan (Eleme)
    NT); The/** * Name Checker implementation class, which inherits the new elementscanner6<br> * provided in JDK 1.6, will access elements in the abstract syntax tree in visitor mode * * Private CLA SS Namecheckscanner extends Elementscanner6<void, void> {/** * This method is used to check the Java class * *
            Override public Void Visittype (typeelement E, Void p) {Scan (e.gettypeparameters (), p);
            Checkcamelcase (E, true);
            Super.visittype (E, p);
        return null; /** * Check method name is legal/@Override public Void visitexecutable (executableelement E
                , Void p) {if (e.getkind () = = method) {Name name = E.getsimplename (); if (Name.contentequals (E.getenclosingelement (). Getsimplename ()) messageR.printmessage (WARNING, "a common method" "+ name +" "should not repeat with class name, avoid confusion with constructors", e);
            Checkcamelcase (E, false);
            } super.visitexecutable (E, p);
        return null; /** * Check variable naming is legal/@Override public Void visitvariable (variableelement E, Vo ID p) {//If this variable is an enumeration or a constant, name the check in uppercase, otherwise check if (e.getkind () = = Enum_constant | | e.getcons Tantvalue ()!= null | |
            Heuristicallyconstant (e)) Checkallcaps (e);
            else Checkcamelcase (E, false);
        return null;
            /** * To determine whether a variable is constant */private Boolean heuristicallyconstant (Variableelement e) {
            if (E.getenclosingelement (). Getkind () = = INTERFACE) return true;
                else if (e.getkind () = = FIELD && e.getmodifiers (). Containsall (Enumset.of (Public, STATIC, FINAL))
            return true;
   else {             return false; }/** * Checks whether the incoming element conforms to the camel-named method and, if not, outputs a warning message/private void Checkcamelcase (El
            Ement E, Boolean initialcaps) {String name = E.getsimplename (). toString ();
            Boolean previousupper = false;
            Boolean conventional = true;

            int firstcodepoint = name.codepointat (0);
                if (Character.isuppercase (Firstcodepoint)) {Previousupper = true;
                    if (!initialcaps) {messager.printmessage (WARNING, name "+ name +" "should begin with a lowercase letter", e);
                Return } else if (Character.islowercase (Firstcodepoint)) {if (initialcaps) {m
                    Essager.printmessage (WARNING, "name" "+ name +" "should begin with a capital letter", e);
                Return

            } else conventional = false; if (conventional) {int CP = FirstcoDepoint; for (int i = Character.charcount (CP); I < name.length (); i + = Character.charcount (cp)) {CP = name.
                    Codepointat (i); if (Character.isuppercase (CP)) {if (previousupper) {conventional = f
                            Alse;
                        Break
                    } Previousupper = true;
                else Previousupper = false; } if (!conventional) messager.printmessage (WARNING, name "+ name +" "should conform to the camel-style nomenclature (
        Camel case Names) ", e); /** * Uppercase name check, requires that the first letter must be an uppercase letter, the remainder can be an underscore or capital letter */private void Checkallcaps (Element E

            {String name = E.getsimplename (). toString ();
            Boolean conventional = true;

            int firstcodepoint = name.codepointat (0); if (!
   Character.isuppercase (Firstcodepoint))             conventional = false;
                else {Boolean previousunderscore = false;
                int cp = Firstcodepoint; for (int i = Character.charcount (CP); I < name.length (); i + = Character.charcount (cp)) {CP = name.
                    Codepointat (i); 
                            if (cp = = (int) ' _ ') {if (previousunderscore) {conventional = false;
                        Break
                    } Previousunderscore = true;
                        else {Previousunderscore = false; if (! Character.isuppercase (CP) &&!
                            Character.isdigit (CP)) {conventional = false;
                        Break '}} ' if (!conventional) messager.printmess Age (WARNING, "constant" "+ name +" "should be all uppercase letters orUnderlined and preceded by a letter ", e);    }
    }
}

Finally, a poor code coding specification code is provided:

public class Badly_named_code {

    enum colors {
        red, blue, Green;
    }

    static final int _forty_two =;

    public static int not_a_constant = _forty_two;

    protected void Badly_named_code () {return
        ;
    }

    public void Notcamelcasemethodname () {return
        ;
    }
}
3.4.3: Running and testing

First compile Namechecker.java and Namecheckprocessor.java with Javac, then Javac-processor namecheckprocessor Badly_named_code.java command to compile this sample code. 3.4.3: Other application cases

Hibernate Validator Annotation Processor, Project Lombok and so on.

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.