自动将公共更改为私有(Java)
我正在对从其他语言翻译成 Java 的代码进行重构,我想自动完成它。我的问题是,我有很多不是私有的方法,但只是在声明它们的同一个类中调用,我想将它们设为私有。我有很多课程,我想是否有什么可以帮助我半自动地完成它,我想知道。
你知道我是否可以寻找这些方法来快速将它们设为私有吗?我正在使用 Eclipse。
I am doing a refactoring on code is translated from other languages into Java and I want to do it automatically. My problem is that I have a lot of methods that aren't private but are just called in the same class that they are declared and I want to make them private. I have a lot of classes and I guess if there is something that can help me to do it semi-automatically I would like to know it.
Do you know if I can look for these methods to make them private fastly? I am using Eclipse.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
全部替换是一种选择。
但是我建议你不要这样做。
private
和public
是为程序员准备的。如果您只从类本身调用一个方法,并不自动意味着它必须是私有
。您能做的最好的事情就是一次浏览它们并问自己“这个方法是否应该成为公共接口的一部分?”。就我个人而言,每当我在需要使用的类中遇到
private
方法时,99% 的情况下我都会将其保留为private
并寻找解决方法。那是因为我假设代码的原始作者知道他在做什么。当然,这并不总是适用。private
是一个意图声明。这就像在说 - 如果您需要在课堂之外使用它,那么您就做错了。你不应该需要这个。Replace all is one option.
But I suggest you don't do it.
private
andpublic
are there for the programmer. If you only call a method from the class itself, it doesn't automatically mean it has to beprivate
. The best thing you can do is go through them one at a time and ask yourself "should this method be part of the public interface or not?".Personally, whenever I encounter a
private
method in a class which I need to use, 99% of the time I leave itprivate
and look for a workaround. That's because I assume the original author of the code knew what he was doing. Of course, this doesn't always apply.private
is a statement of intent. It's like saying - if you need to use this from outside the class, you're doing something wrong. You shouldn't need this.需要注意的一件事是,由于它被假定为公共范围,因此您的类之外可能有类调用该方法。如果您能够保证自己有所有可能的代码调用此函数。您还可以通过鼠标右键单击该方法并使用“引用”或(ctrl+shift+G)来检查该方法是否正在 Eclipse 中使用,以确保没有任何地方调用该方法。
要真正实现从公共到私有的更改,搜索和替换可能是您最好的选择。
One thing to be aware of is, since it is assumed public scope, you may have classes outside of your class calling the method. If you are able to guarantee yourself that you have all possible code calling this. You can also check if the method is being use in eclipse by right mouse click on the method and use the Reference or (ctrl+shift+G) to make sure that no where is calling this method.
To actually making the change from public to private, a search and replace is probably your best bet.
也许一种方法是在选定的文档上用“私人”单词替换“公共”单词,并使用“全部替换”功能。但是,如果除方法签名之外的某些代码的内容中有“public”,例如可能在字符串内,它会产生副作用。
替换您选择的所有方法签名后,请再检查一次以确保它们符合您想要的方式。
Maybe one way would be replacing "public" words with "private" words on selected documents and with "Replace all" function. But it has side effects if you have "public" in the content of some code other than the method signature, e.g. inside a String maybe.
After replacing all method signatures you select, check one more time to make sure them they are in the way you wanted.