如何在 Eclipse中更快地编写 Java …

来源:互联网 发布:玉溪软件开发公司 编辑:程序博客网 时间:2024/06/05 06:58

在日常使用的 Eclipse 特性中,Source菜单中用于代码生成的项目是用得最多的。在花了很多时间来学习如何有效使用它们后,掌握了这些特性,你就能够很快地构建 Java类了。

例如,创建新类时,我不再花时间编写 setter 和getter(访问器),也不用编写大部分的构造器。相反,我创建类并快速在类中输入私有变量,如下 所示。


public class test {

 private String  year;
 private String  month;
 private String  day;

 

 

然后,单击 Source > Generate Getters andSetters,选择刚才输入的、想用公共访问器公开的私有变量。要使用构造器初始化部分变量,单击Source > Generate Constructor usingFields以快速创建构造器。只需点击几下鼠标,一个类就差不多创建完成了,具体情况取决于要用该类实现什么功能。

如何在 <wbr>Eclipse中更快地编写 <wbr>Java <wbr>代码
public class test {
 
 
 private String  year;
 private String  month;
 private String  day;
 
 public test(String year, String month, Stringday) {
  super();
  this.year = year;
  this.month = month;
  this.day = day;
 }
 
 public String getYear() {
  return year;
 }
 public void setYear(String year) {
  this.year = year;
 }
 public String getMonth() {
  return month;
 }
 public void setMonth(String month) {
  this.month = month;
 }
 public String getDay() {
  return day;
 }
 public void setDay(String day) {
  this.day = day;
 }
生成toString(),使用 Source> Generate toString()来完成
@Override
 public String toString() {
  return "test [" + (year != null? "year=" + year + ", " : "")
    +(month != null ? "month=" + month + ", " : "")
    +(day != null ? "day=" + day : "") + "]";
 }

 

使用hashCode()equals()

有时,您需要创建一些规则,根据实际的字段值将您的对象变为相等的对象。这时,使用 Eclipse GalileohashCode()equals() 生成功能真的很方便。这不同于equals() 的默认行为,因为即使默认拥有相同值的对象也不会是相等的。

 

public static void main(String[] args) {
  test test = new test("2012","08", "03");
  test test1 = new test("2012","08", "03");
  System.out.println(test.toString());
  System.out.println(test1.toString());
  System.out.println("test equalstest1:"+test.equals(test1));
 }

 

输出:test [year=2012, month=08, day=03]
    test [year=2012, month=08, day=03]
    test equals test1:false

可以看出所有属性值都是相同的,但是比较结果却是false。

要改变这种行为,单击 Source > Generate hashCode()and equals() 以生成 equals()方法的一个新版本,新的方法将比较所有字段,如下所示。生成新的equals()方法:

@Override
 public boolean equals(Object obj) {
  if (this == obj)
   returntrue;
  if (obj == null)
   returnfalse;
  if (getClass() !=obj.getClass())
   returnfalse;
  test other = (test) obj;
  if (day == null) {
   if (other.day!= null)
    returnfalse;
  } else if(!day.equals(other.day))
   returnfalse;
  if (month == null) {
   if(other.month != null)
    returnfalse;
  } else if(!month.equals(other.month))
   returnfalse;
  if (year == null) {
   if(other.year != null)
    returnfalse;
  } else if(!year.equals(other.year))
   returnfalse;
  return true;
 }

再次比较结果:

test [year=2012, month=08, day=03]
test [year=2012, month=08, day=03]
test equals test1:true
通过这样,一个类便很快创建起来了,减少很多手工代码量。


0 0