我想做类似下面的事情,但它不起作用。我的目标是能够将函数调用嵌套到静态辅助类中以获得更多简洁。
public class StaticHelper {
public static Class<StaticHelper> doSomthing() {
System.out.println("I just did something !!");
return StaticHelper.class;
}
public static Class<StaticHelper> doSomthingElse() {
System.out.println("I just did something else !!");
return StaticHelper.class;
}
public static void main(String[] args) {
// Does not compiles
StaticHelper.doSomthing().doSomthingElse();
}
}
这可能吗?如果是这样,上面的简单示例将非常有用。
答案 0 :(得分:2)
这是不可能的,但使用static imports是。
public class StaticHelper {
public static void doSomething() {
System.out.println("I just did something !!");
}
public static void doSomethingElse() {
System.out.println("I just did something else !!");
}
}
在另一个班级:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething(); // calls static methods from StaticHelper
doSomethingElse();
}
}
或 - 如果方法是逻辑连接的 - 您可以有一个静态工厂方法,其余的是实例方法:
public class StaticHelper {
public static void beginDoingSomething() {
// static factory method - you can pass parameters to it if needed
System.out.println("I just did something !!");
return new StaticHelper();
// if needed, initialize the instance with the parameters
}
public StaticHelper andDoSomethingElse() {
// instance method
// can use the instance parameters (passed to the constructor in the static factory method)
// or use parameters passed to this method
System.out.println("I just did something else !!");
return this;
// returns this for chaining
}
}
在另一个班级:
import static StaticHelper.*;
class Other {
public static void main(String[] args) {
doSomething().andDoSomethingElse().andDoSomethingElse();
}
}
如果你很好地命名方法,你可以形成一个句子:
validate(object).checkEmail().checkName().checkTelephoneStartsWith("+11");
其中validate(object)
是一个静态工厂方法,为给定的object
构建一个新的验证器实例。
答案 1 :(得分:2)
我想你想要这样的东西。
public class StaticHelper {
private final static StaticHelper INSTANCE = new StaticHelper();
public static StaticHelper doSomthing(){
System.out.println("I just did something !!");
return INSTANCE;
}
public static StaticHelper doSomthingElse(){
System.out.println("I just did something else !!");
return INSTANCE;
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
}
或其他方式
public class StaticHelper {
public static SomeClass doSomthing(){
return new SomeClass().doSomthing();
}
public static SomeClass doSomthingElse(){
return new SomeClass().doSomthingElse();
}
public static void main(String[] args) {
StaticHelper.doSomthing().doSomthingElse();
}
private static class SomeClass {
public SomeClass doSomthing(){
System.out.println("I just did something !!");
return this;
}
public SomeClass doSomthingElse(){
System.out.println("I just did something else !!");
return this;
}
}
}