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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Yes it's possible to call static method of a class without using Class reference by using static import.
ex:
It's preferable to use this way if static methods are used in lot of places in the class.
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?
Yes. But, you would need to
import
it. Specifically,import static
. Like,Then you can call
someMethod(String)
like