Java仅通过一个对象发送类参数

来源:爱站网时间:2021-09-27编辑:网友分享
是否可以将对象创建为“仅用于参数”?例如:class MyClass {public String a;公众号b; public MyClass(Object params){this.a = params.a!== ...

问题描述


是否可以将对象创建为“仅用于参数”?例如:

class MyClass {
    public String a;
    public Number b;

    public MyClass(Object params) {
        this.a = params.a !== null ? params.a : "default";
        this.b = params.b !== null ? params.b : 0;
    }
}

void main() {
    MyClass myclass1 = new MyClass(new Object() {
        String a = "hey";
    });

    MyClass myclass2 = new MyClass(new Object() {
        Number b = 123;
    });

    MyClass myclass3 = new MyClass(new Object() {
        String a = "!!!";
        Number b = 5;
    });
}

显然,此代码不起作用,我尝试了很多方法来尝试复制它,也许使用模板(通用)?

预期结果将是:

myclass1.a == "hey";
myclass1.b == 0;

myclass2.a == "default";
myclass2.b == 123;

myclass3.a == "!!!";
myclass3.b == 5;

思路:


您可以使用Builder pattern创建所需的实例:

public final class MyClass {

    private final String str;
    private final Number number;

    public static Builder builder() {
        return new Builder();
    }

    private MyClass(Builder builder) {
        str = builder.str;
        number = builder.number;
    }

    public String getStr() {
        return str;
    }

    public Number getNumber() {
        return number;
    }

    public static final class Builder {

        private String str = "default";
        private Number number = 0;

        private Builder() {
        }

        public MyClass build() {
            return new MyClass(this);
        }

        public Builder str(String str) {
            this.str = str;
            return this;
        }

        public Builder number(Number number) {
            this.number = number;
            return this;
        }

    }
}

Demo:

public static void main(String... args) {
    MyClass myclass1 = MyClass.builder().str("hey").build();
    MyClass myclass2 = MyClass.builder().number(123).build();
    MyClass myclass3 = MyClass.builder().str("!!!").number(5).build();
}

如果您不想使用Builder pattern,则可以使用类重写:

public class MyClass {

    public String getStr() {
        return "default";
    }

    public Number getNumber() {
        return 0;
    }

}

public static void main(String... args) throws IOException {
    MyClass myclass1 = new MyClass() {
        @Override
        public String getStr() {
            return "hey";
        }
    };

    MyClass myclass2 = new MyClass() {
        @Override
        public String getStr() {
            return "hey";
        }

        @Override
        public Number getNumber() {
            return 123;
        }
    };

    MyClass myclass3 = new MyClass() {
        @Override
        public String getStr() {
            return "!!!";
        }

        @Override
        public Number getNumber() {
            return 5;
        }
    };
}

上一篇:如何匹配字符串中所有不以英语字母开头的数字的所有组合,在Java中都是常规匹配

下一篇:Spring MongoDB标准更新

您可能感兴趣的文章

相关阅读

热门软件源码

最新软件源码下载