我有一个名为 Tools 的实用程序类。在另一个类中,如何直接评估 Tools 中的方法,而不将方法设置为 static
并使用 Tools.methodName();
前缀?
相反,我希望能够编写 methodName();
并完成这项工作。我知道你可以使用
import packagename.Tools
但我的 IDE 仍然希望我将方法更改为静态
。例如:
实用类:
package jsmash;
public class Tools {
public boolean expect(char c, int i) {
return Filler.fileContents[i] == c;
}
}
我希望能够做什么:**
package jsmash
import jsmash.Tools;
public class Test {
void use() {
expect('c', 32); // directly call the expect method without *Tools.* prefix
}
}
最佳答案
- 使方法
静态
- 静态导入方法
像这样:
public class Tools {
public static boolean expect(char c, int i) { //dont worry about what this method is actually doing
if(Filler.fileContents[i] == c) return true;
else return true;
}
}
然后使用:
import static jsmash.Tools.expect;
public class Test {
void use() {
expect('c', 32);
}
}
您还可以简单地:
import static jsmash.Tools.*;
批量导入所有静态方法(和字段)。
关于java - 如何在其他类中直接访问我的库类中的方法? java ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34147509/