首页 > 编程语言 >在 Eclipse Galileo 中更快地编写 Java 代码使用新的 toString() 生成器

在 Eclipse Galileo 中更快地编写 Java 代码使用新的 toString() 生成器

时间:2023-07-31 10:35:42浏览次数:42  
标签:Java String 生成器 make year Eclipse toString Automobile 清单


http://www.ibm.com/developerworks/cn/opensource/os-eclipse-codegen/

这个代码生成技巧使用 Eclipse Galileo 中的新特性。但是,您也可以使用在这里介绍的、旧版本 Eclipse(如 Ganymede)中的某些技巧(如生成 getters 和 setters)。

代码生成概述

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

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

清单 1. 私有变量

public class Automobile { private String make; private String model; private String year;}


然后,单击 Source > Generate Getters and Setters,选择刚才输入的、想用公共访问器公开的私有变量。要使用构造器初始化部分变量,单击 Source > Generate Constructor using Fields 以快速创建构造器。只需点击几下鼠标,一个类就差不多创建完成了,具体情况取决于要用该类实现什么功能(见清单 2)。理想的情况是,新创建的代码应该遵守此前在 Eclipse 首选项中设置的代码格式规则。

清单 2. 自动创建构造器和访问器

public class Automobile { private String make; private String model; private String year; public String getMake() { return make; } public Automobile(String make, String model, String year) { super(); this.make = make; this.model = model; this.year = year; } public void setMake(String make) { this.make = make; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getYear() { return year; } public void setYear(String year) { this.year = year; }}


除了可以用 Source 菜单项生成代码外,还可以通过使用 Ctrl+Space 快捷键编写许多公共代码块来生成大量代码。要弄清生成特定的代码块需要使用的名称,查看 Preferences 窗口。例如,输入 lazy,然后按下 Ctrl+Space,这将生成用于延迟加载的 Java 代码。




回页首

代码生成设置

新方法的代码生成设置在 Java > Code Style > Code Templates 下面的 Preferences 窗口中修改。

图 1. Java > Code Style > Code Templates 首选项



总结您的最佳实践


作为几个项目的技术主管,我已经确认了一些希望在我们的项目中采用的最佳实践。我将它们放在 Java 代码模板中,供团队成员导入。


Preferences 窗口中的 Java > Editor > Code Templates 设置根据名称列示模板(见图 2)。仔细检查 Eclipse 带有的模板。您可以添加自己的模板,也可以导入模板。

图 2. Java > Editor > Code Templates 首选项





回页首

使用 toString() 生成功能

Eclipse Galileo 中的一个新特性是能够生成 toString() 方法。默认情况下,toString() 方法输出一个类的表示,这也许不能真正显示您想要查看的属性。检查清单 3 中的 main 方法。

清单 3. 使用 toString() 输出 Automobile

public class Main { public static void main(String[] args) { Automobile auto = new Automobile("Toyota", "Corolla", "1993"); System.out.println(auto.toString()); }}


这个应用程序的输出如清单 4 所示。

清单 4. Main 方法的输出

Automobile@77df38fd


在 Galileo 之前,我必须手工编写 toString() 方法。尽管编写这个小类并不是太费力,但如果一个类拥有许多字段,编写工作就会花费一些时间。我可能想做很多事情(比如检查一些空值),而不仅仅是串联一些值。也许我想使用一个 StringBuilder 来获得更好的性能。但是对于 Galileo,我可以使用 Source > Generate toString() 来完成上述所有任务,如图 3 所示。

图 3. 生成 toString()


单击 Finish 之后,新的 toString() 方法如清单 5 所示。

清单 5. 自动生成的 toString() 方法

... @Override public String toString() { return "Automobile [" + (make != null ? "make=" + make + ", " : "") + (model != null ? "model=" + model + ", " : "") + (year != null ? "year=" + year : "") + "]"; }...


现在,main 方法运行时,输出如清单 6 所示。

清单 6. 自动生成的 toString() 方法的输出

Automobile [make=Toyota, model=Corolla, year=1993]





回页首

格式化字符串

即使清单 6 中显示的输出比清单 4 中的原始输出更具描述性,但调整一下输出格式使其更具可读性可能会更好,比如 “1993 Toyota Corolla (Automobile)”。自定义模板允许您调整 toString() 方法生成的输出。

删除 toString() 方法并再次单击 Source > Generate toString()。这次:

  1. 单击 String format 下拉列表旁边的 Edit
  2. 单击 New

    图 4. 添加一个新格式

  3. Pattern 中输入类似 ${member.value} ${otherMembers} (${object.className}) 的内容,给它起个名称,然后单击 OK

选中新模式,在 Generate toString() 上单击 OK。新代码如清单 7 所示。

清单 7. 更新后的 toString() 方法

... @Override public String toString() { return (make != null ? make + " " : "") + (model != null ? model + " " : "") + (year != null ? year : "") + " (Automobile)"; }...


现在,运行 main 方法,Automobile 对象的 toString() 输出如清单 8 所示。

清单 8. Automobile 对象的 toString() 方法的输出

Toyota Corolla 1993 (Automobile)





回页首

处理数组

您还能使用 toString() 生成器处理数组。清单 9 展示了一个称为 options 的新的字符串数组。

清单 9. options 字符串数组

Automobile auto = new Automobile("Toyota", "Corolla", "1993"); String[] options = new String[] { "Automatic Transmission", "Power Brakes", "Power Windows" }; // new generated method after adding private String[] options; auto.setOptions(options); System.out.println(auto.toString()); // prints this: // Toyota Corolla [Ljava.lang.String;@defb836 1993 (Automobile)


通常,原生 toString() 方法输出的数组表示就像对象的原始表示一样,并不真正显示内容。但是,选项 List contents of arrays instead of using native toString 改变了这种情况。选中该选项,重新生成 toString() 方法,新的输出如清单 10 所示。

清单 10. 重新生成的 toString() 方法的输出

Toyota Corolla [Automatic Transmission, Power Brakes, Power Windows] 1993 (Automobile)





回页首

限制输出

如果某些数组非常大,可以通过选中 Limit number of items in arrays/collections/maps 并设置限制来约束输出的内容(见图 5)。这样做可以阻止 toString() 方法输出过多内容。

图 5. 输出数组内容并施加限制


清单 11 显示了将限制设置为 2 的情况。

清单 11. 将数组内容限制为 2

Toyota Corolla [Automatic Transmission, Power Brakes] 1993 (Automobile)





回页首

使用 hashCode()equals()

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

清单 12. equals() 方法的默认行为

public class Main { public static void main(String[] args) { Automobile auto = new Automobile("Toyota", "Corolla", "1993"); String[] options = new String[] { "Automatic Transmission", "Power Brakes", "Power Windows" }; auto.setOptions(options); Automobile auto2 = new Automobile("Toyota", "Corolla", "1993"); String[] options2 = new String[] { "Automatic Transmission", "Power Brakes", "Power Windows" }; auto2.setOptions(options2); System.out.println("Autos 1 and 2 are equal(): " + auto.equals(auto2)); }}


即使所有属性值设置为相同的值,代码执行时也会输出 Auto 1 and 2 are equal(): false

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

清单 13. 用新的 equals() 方法比较所有字段

@Override public int hashCode() { // snipped... } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Automobile other = (Automobile) obj; if (make == null) { if (other.make != null) return false; } else if (!make.equals(other.make)) return false; if (model == null) { if (other.model != null) return false; } else if (!model.equals(other.model)) return false; if (!Arrays.equals(options, other.options)) return false; if (year == null) { if (other.year != null) return false; } else if (!year.equals(other.year)) return false; return true; }


现在,执行这段代码时,这两个对象使用覆盖后的 equals() 方法进行比较,所以二者是相同的。

Eclipse Galileo 中的另一个新特性是为 if 语句生成代码块的能力。如果您还没有将 Source > Clean Up 配置为将单行 if 语句转换为代码块,这个新特性很有用。避免使用单行 if 语句通常被认为是最佳实践,因此许多人愿意确保他们的代码遵守这个最佳实践。




回页首

结束语

Galileo 中生成 toString() 方法的新特性增强了 Eclipse 生成大量 Java 代码的能力。通过实践,您可以明确哪些代码必须手工输入,哪些代码可以自动生成,从而减少您的工作量。

 

标签:Java,String,生成器,make,year,Eclipse,toString,Automobile,清单
From: https://blog.51cto.com/u_16174476/6905829

相关文章

  • Eclipse中如何恢复已删除文件
    http://tech.ddvip.com/2008-12/122855149998075.htmlhttp://zhangjunhd.blog.51cto.com/如果,在开发中,(Eclipse)删除了一些文件后又发现需要这些文件该怎么办?现在删除T1.java和T4.properties。鼠标右键点击项目名ZJ,选择RestorefromLocalhistory。选择需要恢复的文......
  • Java NIO系列教程(十一) Pipe
    JavaNIO管道是2个线程之间的单向数据连接。Pipe有一个source通道和一个sink通道。数据会被写到sink通道,从source通道读取。这里是Pipe原理的图示: 创建管道通过Pipe.open()方法打开管道。例如:Pipepipe=Pipe.open();向管道写数据要向管道写数据,需要访问sink通道。像这样:Pi......
  • 使用Eclipse构建Maven的SpringMVC项目
    使用Eclipse构建Maven的SpringMVC项目      首先Eclipse需要安装Maven的插件,地址:http://m2eclipse.sonatype.org/sites/m2e。     用MyEclipse安装Maven插件,建出的Maven项目有些问题。一是,发布tomcat的时候resources总是不会被发布到tomcat下;二是,把WEB-INF下的cla......
  • Java NIO系列教程(三) Buffer
    JavaNIO中的Buffer用于和NIO通道进行交互。如你所知,数据是从通道读入缓冲区,从缓冲区写入到通道中的。缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成NIOBuffer对象,并提供了一组方法,用来方便的访问该块内存。下面是NIOBuffer相关的话题列表: Buffe......
  • reactor.core.Exceptions$ErrorCallbackNotImplemented: java.lang.IndexOutOfBoundsE
    生产环境好好的,突然前端请求全部跨域,请求500。gateway报错。reactor.core.Exceptions$ErrorCallbackNotImplemented:java.lang.IndexOutOfBoundsException:Index:0,Size:0。所有的接口都报。原因由于gateway也集成了springboot-admin,开启了应用程序的actuator端点,导致......
  • #yyds干货盘点#JavaScript正则表达式(手机号码、邮箱、日期)
    JavaScript正则表达式(手机号码、邮箱、日期)在平时的工作中,经常会遇到一些验证的功能,其中如号码、邮箱、日期之类的验证,但是在平常使用时,直接就抄了一份用,并没有很详细的研究过,所以就在这儿记录了一些常用的表达式,慢慢学习的同时,也分享给大家。手机号码由于现在虚拟号码的使用,所以......
  • 深入探究Java 17中的外部函数和内存API
    导言Java17作为JDK的最新版本,带来了许多令人兴奋的新特性和改进。在本篇博客中,我们将聚焦于Java17中的两个重要主题:外部函数(ForeignFunction)和内存API(MemoryAPI)。这两个功能的引入为Java开发者们提供了更多的灵活性和性能优势,让我们一起深入探究它们的作用和用法。一、外部函数......
  • GAN中的生成器和判别器
    在生成对抗网络(GAN)中,生成器(Generator)和判别器(Discriminator)是两个核心组件,分别负责生成和判别。生成器是GAN的一个网络模型,它接收一个随机噪声作为输入,并通过一系列的转换和映射操作,生成出一个伪造的样本。生成器的目标是将随机噪声转换为与真实样本相似的样本,以尽可能地骗过判别......
  • JVM调优篇:探索Java性能优化的必备种子面试题
    JVM内存模型首先面试官会询问你在进行JVM调优之前,是否了解JVM内存模型的基础知识。这是一个重要的入门问题。JVM内存模型主要包括程序计数器、堆、本地方法栈、Java栈和方法区(1.7之后更改为元空间,并直接使用系统内存)。正常堆内存又分为年轻代和老年代。在Java虚拟机中,年轻代用......
  • java基础——泛型
    泛型的引入看下面这段代码:privatestaticintadd(inta,intb){System.out.println(a+"+"+b+"="+(a+b));returna+b;}privatestaticfloatadd(floata,floatb){System.out.println(a+"+"+b+"="+......