简体   繁体   English

Eclipse如何生成setter和getter?

[英]How does Eclipse generate setters and getters?

Just curious to know how Eclipse creates setters and getters (not how to myself). 只是想知道Eclipse是如何创建setter和getter的(而不是我自己的)。 I am sure it must be Java reflection but just wanted to seek some more information. 我确信它一定是Java的反映,但只是想寻求更多信息。

Eclipse actually embeds an entire compiler to allow it to do incremental compilation and still give you useful information when you have a syntax error in your code. Eclipse实际上嵌入了整个编译器,以使其能够进行增量编译,并且在代码中出现语法错误时仍会为您提供有用的信息。 The generators look at the abstract syntax tree (AST) representation of the code, identify the fields, and use the JavaBeans formula to create getters and setters for them. 生成器查看代码的抽象语法树(AST)表示形式,标识字段,并使用JavaBeans公式为其创建getter和setter。 You can use the "Outline" view in Eclipse to see a graphic representation of Eclipse's model of the class. 您可以在Eclipse中使用“概述”视图来查看Eclipse类模型的图形表示。

step1:

A simple User.java, with 4 fields, but no getters and setters method.

 public class user{

 private String firstname();
 private  String lastname();
 private String username();
 private String password();

 }
  step2: Generate It

 Right click on the file, select “Source” –> “Generate Getters and Setters…”

-> Choose which field you want to generate, and click on “OK” button.

 step3:

 All selected getters and setters methods will be generated automatically.


   public class user{

    private String firstname();
     private  String lastname();
    private String username();
     private String password();
   public String getFirstName(){
   return firstname;
  }
   public void setFirstName(String firstname){
   this.firstname=firstname;
   }
    public String getFirstName(){
   return lastname;
  }
   public void setLastName(String lastname){
   this.lastname=lastname;
   }
    public String getUserName(){
   return username;
  }
   public void setUserName(String username){
   this.username=username;
   }
     public String getPasword(){
   return password;
  }
   public void setPassword(String password){
   this.password=password;
   }
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM