有没有更好的方法来构建这个<T>对象?

问题描述 投票:0回答:1

对于下面的方法,是否有更好的方法来构建返回的对象? 它的类型是

<T>

第一个

input
参数与返回的对象具有相同的类型。

最后一个

builder
参数让我着急。 它当前指向每个 T 类中的静态工厂方法。

如果你想避免传递

builder
参数,你会如何处理?

(我不想诉诸演员。)

public <T extends FourVector> T transformVector(T input, TransformInto direction, Function<Map<Axis, Double>, T> builder) {
  //the core calculation uses matrices, so we convert back and forth like so
  Matrix input_matrix = Matrix.asMatrix(input);
  Matrix result = Λ(direction.sign()).times(input_matrix);
  //I need to build a new T object here; hence the builder param
  return builder.apply(asComponents(result));
}
java function generics constructor
1个回答
0
投票

我尝试了大约 6 种不同的变化。

我能想到的最好方法是创建一个显式的

Builder
接口来构建所需的对象。

基本思想是传入的

input
对象已经是正确的类型 T,因此要求该对象构建相同类型 T 的新对象是有意义的。

private <T extends FourVector & Builder<T>> T transformVector(T input, TransformInto direction) {
    //the core calculation uses matrices, so we convert back and forth like so
    Matrix input_matrix = Matrix.asMatrix(input);
    Matrix output_matrix = lambdaMatrix(direction.sign()).times(input_matrix);
    return input.build(fromComponents(output_matrix));
  }

使用

Builder
接口作为从较低层数据结构到所需高层数据结构的转换器:

public interface Builder<T> {
  
  /** Build a new T object out of the given components. */
  public T build(Map<Axis, Double> components);

}

这方面的不寻常之处在于,对象创建不是通过构造函数,而是通过常规对象方法。

© www.soinside.com 2019 - 2024. All rights reserved.