简体   繁体   English

通用方法<?>类型参数

[英]Generic method <?> Type Arguments

In a library for charts I found the following class:在图表库中,我找到了以下类:

public class SeriesBuilder<T> {
    private T[] data;

    private SeriesBuilder() {
    }

    public static SeriesBuilder<?> get() {
        return new SeriesBuilder();
    }
    
    public SeriesBuilder<T> withData(T... data) {
        this.data = data;
        return this;
    }

    public Series<T> build() {
        Series<T> series = new Series<T>();
        series.setData(data);
        return series;
    }
}

Using code:使用代码:

SeriesBuilder.get()
             .withData(<<<<<???>>>>)
             .build()

I'm not able to find out how to use the class because of the <?> Type.由于 <?> 类型,我无法找出如何使用该类。 I can't find an argument that fullfills the signature.我找不到满足签名的论点。 How to use this?这个怎么用?

I'm not able to find out how to use the class because of the <?> Type.由于 <?> 类型,我无法找出如何使用该类。 I can't find an argument that fullfills the signature.我找不到满足签名的论点。 How to use this?这个怎么用?

You pretty much can't use it.你几乎不能使用它。 There is no way to obtain a SeriesBuilder instance except via SeriesBuilder.get() , and the type parameter of an instance that you obtain that way is unknown -- in fact, what get actually instantiates is the raw type.除了通过SeriesBuilder.get()之外, SeriesBuilder.get()获得SeriesBuilder实例,并且您通过这种方式获得的实例的类型参数是未知的——实际上, get实际实例化的是原始类型。 You should be able to produce a series of null s if you wish.如果您愿意,您应该能够生成一系列null

There cannot even be any subclasses of SeriesBuilder (that might be more usable), because its only constructor is private.甚至不能有SeriesBuilder任何子类(可能更有用),因为它唯一的构造函数是私有的。

Without putting too fine a point on it, this SeriesBuilder is pretty much an abomination.没有过多说明它,这个SeriesBuilder几乎是令人憎恶的。 There is an argument to be made for preferring factory methods (such as SeriesBuilder.get() ) over constructors, but that implementation is terrible.有一个论点是优先使用工厂方法(例如SeriesBuilder.get() )而不是构造函数,但这种实现很糟糕。 In addition to the type parameter issues, it does not initialize the resulting object to a valid state.除了类型参数问题之外,它不会将结果对象初始化为有效状态。 That has to be done separately via withData() , so what is the point of get() supposed to be?这必须通过withData()单独完成,那么get()是什么?

I'm inclined to think that whoever wrote that was looking for something that would have been better expressed via this variation on withData() :我倾向于认为,无论是谁写的,都是在寻找通过withData()这种变体可以更好地表达的东西:

    public static <T> SeriesBuilder<T> withData(T ... data) {
        SeriesBuilder<T> builder = new SeriesBuilder<>();

        builder.data = data;
        return builder;
    }

You might use that as你可以用它作为

SomeType item1 = /* value */;
SomeType item2 = /* value */;
SomeType item3 = /* value */;

Series<SomeType> series =
        SeriesBuilder.withData(item1, item2, item3)
                     .build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM