Non-class functions in Java

▼魔方 西西 提交于 2020-07-03 10:13:16

问题


I'm mostly a c/C++/objective-C programmer, presently working in Java on an android application. My question is simple: I want a utility function, preferably not associated with any class that I can invoke from anywhere in my project (#include of some sort necessary?).

I know I can make a public static function of a class and invoke it as Class.someFunction();. I would like to just have someFunction(); I'm not sure if this is possible in java, or what the syntax for it is.


回答1:


You can achieve the same "effect" by using a static import, by adding the following import in each file that you want to use it in:

import static x.y.Class.someFunction;  // or x.y.Class.*;

...

// some code somewhere in the same file
someFunction();

However, all methods in Java must be part of a class. Static imports just let you pretend (briefly) otherwise.

P.S. This also works for static fields.




回答2:


You could use a static import:

import static com.example.MyUtilityClass.*; // makes all class methods available
// or
import static com.example.MyUtilityClass.myMethod; // makes specified method available

You don't see this used very often because, if overused, it causes harder-to-debug code (see the last paragraph at the link above).

Here's a related question about when it's advisable to use this.




回答3:


Also, following the programming best practices, You should define all such common, frequently used functionality in some utility class where you can define your functions or fields(probably constants- i.e. static and final attributes) that is going to be used/called at different places within the API.

Although, you still need to import the Utility class. Else define such functionality in the top most parent class in your API hierarchy structure, that way you even don't have to import the class.

Hope this helps. thanks....!!!




回答4:


Yeap import static..

For instance:

import static java.lang.Math.max; // Allowing to use max method anywhere in the source
class SomeClass { 
    int m = max( 1, 2 );// m now is 2 due t Math.max( int, int ) 
}


来源:https://stackoverflow.com/questions/6497165/non-class-functions-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!