[英]Eclipse method call refactoring
I'm trying to refactor some code in the following pattern: 我正在尝试以以下模式重构一些代码:
// from
object1.foo(object2).bar() ;
// to
fooBar(object1, object2) ;
where 哪里
For context, the change is due to foo() returning null in some cases, which leads to NullPointerExceptions when bar() is called. 对于上下文,更改是由于foo()在某些情况下返回null所致,这在调用bar()时导致NullPointerExceptions。
fooBar() first checks if null would be returned by foo(), and if so returns a default value, else calls bar() and returns that. fooBar()首先检查foo()是否会返回null,如果是则返回默认值,否则调用bar()并返回它。
I'm using Eclipse, and I'm wondering if there is a good way to do this, instead of manually changing every occurrence using regex in a File Search or something. 我正在使用Eclipse,我想知道是否有一个很好的方法来执行此操作,而不是使用文件搜索中的正则表达式手动更改每次出现的情况。
EDIT - more info in response to comments: 编辑-有关评论的更多信息:
I do not have control over the implementation of foo(). 我无法控制foo()的实现。
Regarding object1 being a subclass of SuperClass: 关于object1是超类的子类:
//in some cases this happens
SuperClass object1 = new SuperClass(/*whatever*/) ;
//in other cases this happens
ChildClass object1 = new ChildClass (/*whatever*/) ;
I though I should mention it, as it might affect how to search for object1. 我应该提一下,因为它可能会影响如何搜索object1。
A [maybe] clearer version of before and after code: 之前和之后的代码的[也许]更清晰的版本:
//before
Object result = object1.foo("a string").bar() ;
//NullPointerException if foo() returns null! :(
//after
Object result = fooBar(object1, "a string") ;
Meanwhile, in a separate utility class, there exists: 同时,在单独的实用程序类中,存在:
public static Object fooBar(SuperClass obj, String str) {
Object result = DEFAULT_RESULT ;
if (obj != null && str != null && obj.fooAble(str)) {
result = obj.foo(str).bar() ;
}
return result ;
}
I found solution even spent on this 3 years of my life! 我发现解决方案甚至花了我这三年的时间! :) :)
Actually solution based on code refactoring that replaces one method call with another. 实际上,基于代码重构的解决方案将一个方法调用替换为另一个方法调用。 Example: Before we have: obj1.method1(){};
示例:在拥有之前: obj1.method1(){};
obj2.method2(obj1){ obj1.method1(); };
After applying eclipse refactoring "Inline ..." we will have every call of obj2.method2(obj1);
在应用eclipse重构“ Inline ...”之后,我们将调用obj2.method2(obj1);
replaced with call obj1.method1();
替换为调用obj1.method1();
So for your case: 因此,对于您的情况:
object1.foo(object2)
which replace all such calls with fooBar(this,object2);
对object1.foo(object2)
任何调用再次应用“ Inline ...”,该调用将所有此类调用替换为fooBar(this,object2);
That's it! 而已!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.