[英]Use Functions in different classes in Java without collecting it in a class as methods
I have some functions collected as methods in a class called func
. 我在一个名为
func
的类中收集了一些作为方法的func
。 I use those methods quite often in different classes. 我经常在不同的类中使用这些方法。 Is there a way in java to call those functions without creating a new object or calling it like this:
func.myFunction();
java中有没有一种方法可以调用这些函数,而无需创建新对象或像这样调用它:
func.myFunction();
? ?
I want: myFunction();
我想要:
myFunction();
There are two issues: 有两个问题:
The first one is easy to solve: if your method doesn't actually use any non-static members (fields or methods) of the class, then simply adding the static
keyword enables you to call it without an instance of the class: 第一个很容易解决:如果您的方法实际上并未使用该类的任何非静态成员(字段或方法),则只需添加
static
关键字即可使您无需类的实例即可调用它:
// in YourClass:
public static void yourMethod() {
//stuff
}
// somewhere else:
YourClass.yourMethod();
And about the second item: I kind-of lied there, you can do that, but you need a static import: 关于第二项:我有点撒谎了, 可以这样做,但是需要静态导入:
// at the beginning of your .java file
import static yourpackage.YourClass.yourMethod;
// later on in that file:
yourMethod();
Also: there are no functions in Java, only methods. 另外:Java中没有函数,只有方法。
Yes, you can mark the methods as static
, and use static imports . 是的,您可以将这些方法标记为
static
,并使用static import 。
Example: 例:
pkg/UtilFunctions.java 包装/ UtilFunctions.java
package pkg;
public class UtilFunctions {
public static int sum(int i1, int i2) {
return i1 + i2;
}
}
Test.java Test.java
import static pkg.UtilFunctions.*;
class Test {
public static void main(String[] args) {
int i = sum(5, 7); // Calls UtilFunctions.sum(...)
}
}
Make them static like public static int myFunction();
使它们像
public static int myFunction();
静态一样public static int myFunction();
and then make static import: import static myclass
: 然后进行静态导入:
import static myclass
:
Foo.java:
class Foo {
public static int method() {return 42;}
...
}
Bar.java
import static Foo.*;
...
System.out.println(method());
You can use a static import. 您可以使用静态导入。
For example this: 例如:
import java.lang.Math;
...
System.out.println(Math.abs(-1.4));
and this: 和这个:
import static java.lang.Math;
...
System.out.println(abs(-1.4));
produce the same result. 产生相同的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.