40

下面怎么打电话start()

package com.example.test;

class Bar {}

public class Foo<K>
{
    final private int count;
    final private K key;

    Foo(Builder<K> b)
    {
        this.count = b.count;
        this.key = b.key;
    }

    public static class Builder<K2>
    {
        int count;
        K2 key;

        private Builder() {}
        static public <K3> Builder<K3> start() { return new Builder<K3>(); }
        public Builder<K2> setCount(int count) { this.count = count; return this; }
        public Builder<K2> setKey(K2 key) { this.key = key; return this; }
        public Foo<K2> build() { return new Foo(this); }
    }

    public static void main(String[] args)
    {
        Bar bar = new Bar();
        Foo<Bar> foo1 = Foo.Builder.start().setCount(1).setKey(bar).build();
        // Type mismatch: cannot convert from Foo<Object> to Foo<Bar>

        Foo<Bar> foo2 = Foo.Builder<Bar>.start().setCount(1).setKey(bar).build();
        // Multiple markers at this line
        // - Bar cannot be resolved
        // - Foo.Builder cannot be resolved
        // - Syntax error on token ".", delete this token
        // - The method start() is undefined for the type Foo<K>
        // - Duplicate local variable fooType mismatch: cannot convert from Foo<Object> to Foo<Bar>

        Foo<Bar> foo3 = Foo<Bar>.Builder.start().setCount(1).setKey(bar).build();
        // Multiple markers at this line
        // - Foo cannot be resolved
        // - Syntax error on token ".", delete this token
        // - Bar cannot be resolved     
    }
}
4

4 回答 4

44

你很接近:

Foo.Builder.<Bar> start().setCount(1).setKey(bar).build();

干杯! :)

PS 如果编译器无法自行推断出方法的类型参数,可以通过调用obj.<Type> method(...).

您可能想要使用的 PPS:

public Foo<K2> build() {
    return new Foo<K2>(this);
}

避免使用原始类型。

于 2010-07-08T14:33:01.800 回答
29

Andrei 的方法还可以,但大多数程序员可能会为这种相当未知的语法而苦恼。使用这种方式可能更容易:

static public <K3> Builder<K3> start(Class<K3> cls) { return new Builder<K3>(); }

Foo<Bar> foo1 = Foo.Builder.start(Bar.class).setCount(1).setKey(bar).build();

仅传递该类以帮助使用泛型类型。它并不漂亮,但至少语法是常识。

另一种选择是立即从泛型类型的对象开始:

Foo<Bar> foo1 = Foo.Builder.startWithKey(bar).setCount(1).build();
于 2010-07-08T14:40:11.070 回答
16

如果您是lombok项目的粉丝并使用它的注解@Builder来实现构建器模式,那么您可以像编写的那样删除所有不必要的代码并用更少的代码来完成。

例子:

@Builder
public class ErrorResponse<T> {
    private String message;
    private List<String> reasons;
    private List<String> details;
    private T data;
}

你可以像这样初始化它:

ErrorResponse<MyData> myDataError = ErrorResponse.<MyData>builder()
.message("My message")
.build();
于 2020-07-02T07:11:19.477 回答
3

我会这样做:

package odmor2018.krit.rtti.builderpattern;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;

public class Person {

    private String firstName;
    private String middleName;
    private String lastName;
    private boolean sex;

    public Person(String firstName, String middleName, String lastName, boolean sex) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
        this.sex = sex;
    }

    public Person() {
    }

    @Override
    public String toString() {
        return "Person{" + "firstName=" + firstName + ", middleName=" + middleName + ", lastName=" + lastName + ", sex=" + sex + '}';
    }

    public static class Builder {

        private final Field[] fields = Person.class.getDeclaredFields();
        private final List<Field> fieldsList = Arrays.asList(fields);
        private final List<String> fNames = fieldsList.stream().map(f -> f.getName()).collect(Collectors.toList());

        private final Person nP = new Person();

        public Builder with(String fName, Object value) {
            if (fNames.contains(fName)) {
                int fInd = fNames.indexOf(fName);
                try {
                    Field f = fields[fInd];
                    f.setAccessible(true);
                    f.set(nP, value);
                } catch (Exception ex) {
                    Logger.getLogger(Person.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            return this;
        }

        public Person createPerson2() {
            return nP;
        }
    }

    public static void main(String[] args) {
        Person p3 = new Person.Builder()
                .with("firstName", "doooobri2")
                .with("sex", false)
                .createPerson2();
        System.err.println("p3:" + p3);
    }
}
于 2018-10-13T14:50:04.077 回答