Can I call a static method of another class withou

2019-06-24 04:40发布

问题:

Can I call a static method of another class without using the class name (in the same package)? There are similar questions but all answers there use class names.

回答1:

Yes. But, you would need to import it. Specifically, import static. Like,

import static com.package.OtherClass.someMethod;

Then you can call someMethod(String) like

someMethod("Like that");


回答2:

It is possible using static imports, however I would like to caution you against using them. Static imports obfuscate where the code lives which makes it harder to understand the code structure. Combined with * imports, humans can no longer determine (without spending a lot of time) the source of the method, although IDEs can.

An example of why it could be bad: let's say you want to see how a problem was solved in a open source project, to get ideas for your own project. And you know what? You can view the code as HTML online. Things are going great! You view the java file you want to see. Then there is this peculiar method "foo". So you search the page for "foo" and there is exactly 1 match (the one you are looking at). There are multiple import static blabla.* lines at top, so that is a dead end. You download the source. Next you do a full text search on the entire project for "foo(" => 5000 matches in 931 files. At which point you no longer have a choice other than loading the project into an IDE if you want to grok the code. You would not have to do any of that if the author would have made it clear where the method lives to begin with. Now, if you do not use * imports, then finding the class is a 2 step process, so it is not nearly as bad. I personally don't use static imports at all. With short yet meaningful names, I find that the explicit type is preferable.

I dislike static imports, because it breaks OO (well, not technically, just conceptually). But this is a personal opinion and the vast majority disagrees with me. So feel free to form your own. The following post has a great discussion on when (not) to use static imports: What is a good use case for static import of methods?



回答3:

Yes it's possible to call static method of a class without using Class reference by using static import.

ex:

import static java.lang.Math.*;

public class compute{
    public double getSqrt(double n){
       return sqrt(n)
    }
}

It's preferable to use this way if static methods are used in lot of places in the class.