简体   繁体   English

如何在自动生成getter和setter时强制Eclipse使用this关键字?

[英]How to force Eclipse to use the this keyword when auto-generating getters and setters?

In Eclipse, is there a way to force the use of the this keyword with referring to class members when auto-generating getters and setters? 在Eclipse中,有没有办法在自动生成getter和setter时强制使用this关键字引用类成员?

For example, I want this getter, auto-generated by Eclipse, 例如,我想要这个由Eclipse自动生成的getter,

public int getId() {
    return id;
}

to be rewritten with 要改写

public int getId() {
    return this.id;
}

Is that possibe? 可能吗? If yes, how? 如果有,怎么样?

ANSWER: 回答:

(The answer is provided by Vitaly , but to make things clear:) (答案由维塔利提供,但为了清楚:)

In the top menu, click Window > Preferences . 在顶部菜单中,单击“ 窗口”>“首选项”
Then, in the Preferences window, click Java > Code Style 然后,在“ 首选项”窗口中,单击“ Java”>“代码样式”
You'll see a checkbox with Qualify all generated field accesses with 'this.' 您将看到一个复选框,其中包含使用'this'限定所有生成的字段访问权限。 Tick this checkbox. 勾选此复选框。

Works like a charm. 奇迹般有效。

(Notice that 'this.' must be 'this'. .) (注意'this.'必须是'this'. 。)

Open Source -> Generate Getters and Setters Source -> Generate Getters and Setters

There is a link at the botton to Code Templates , click it. Code Templates有一个链接,单击它。

Choose - will you change project settings or workspace settings. 选择 - 您将更改项目设置或工作区设置。

In Configure generated code and comments , expand Code and select Getter Body , in pattern add this. Configure generated code and comments ,展开Code并选择Getter Body ,在模式中添加this. .

That's it. 而已。

Note: You can open Code Templates from project properties or from workspace preferences. 注意:您可以从项目属性或工作区首选项中打开Code Templates

Adjust your code template under window->preferences. 在window-> preferences下调整代码模板。 There are a couple of different pages that have code templates. 有几个不同的页面有代码模板。 You'll find the getters and setters in one of them. 你可以在其中一个中找到吸气剂和固定剂。

Or when you generate getters and setters from the source menu, the dialog has a link to the code templates that you can click. 或者,当您从源菜单中生成getter和setter时,该对话框会显示一个指向您可以单击的代码模板的链接。

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

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