简体   繁体   English

如何重构 Eclipse 中的变量类型?

[英]How to refactor variable type in Eclipse?

I want to refactor code like this:我想重构这样的代码:

int x=4;
int y=x;
System.out.println(y);

How can i do this automatically in Eclipse so x's type promotion to long would cause dependent variables to change their types also:我如何在 Eclipse 中自动执行此操作,因此 x 的类型提升为 long 会导致因变量也更改其类型:

long x=4;
long y=x;
System.out.println(y);

? ?

How I usually do is that I change one of the upstream variables to long.我通常的做法是将上游变量之一更改为 long。 This causes Eclipse to give error from each assignment where you offer long instead of int.这会导致 Eclipse 从您提供 long 而不是 int 的每个分配中给出错误。 Then I just select ctrl-1 (Quick-fix) on each of them and pick "change variable x to long".然后我只需在每个上选择 ctrl-1(快速修复)并选择“将变量 x 更改为长”。

This works when the new type is not directly assignable to the old one.当新类型不能直接分配给旧类型时,这是有效的。

I don't think you can do this directly using the refactoring tool in Eclipse.我不认为你可以直接使用 Eclipse 中的重构工具来做到这一点。 However, what you can do is place your cursor over the variable x and hit CTRL + SHIFT + G to find all references in your workspace.但是,您可以做的是将光标放在变量x并按CTRL + SHIFT + G以查找工作区中的所有引用。 This will then allow you to change any dependent references.这将允许您更改任何相关引用。

IntelliJ has this feature (refactor->type migration), but unfortunately, Eclipse doesn't have it yet. IntelliJ 有这个特性(重构->类型迁移),但不幸的是,Eclipse 还没有。 I hope Eclipse will add it soon.我希望 Eclipse 会尽快添加它。

If your field has setter and getter and you have used them in your project, you can first change type of the field manually then refactor its setter and getter methods.如果您的字段具有 setter 和 getter 并且您已在项目中使用它们,您可以先手动更改字段的类型,然后重构其 setter 和 getter 方法。 ei you can change return type of the setter and getter by method refactor. ei 您可以通过方法重构来更改 setter 和 getter 的返回类型。
To refactor a method use:要重构方法,请使用:
Open context menu on the method > Refactor > Change method signature打开方法上的上下文菜单 > 重构 > 更改方法签名

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

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