泛化数组类型,如Object [] .class

时间:2017-09-21 10:27:30

标签: java generics

我想在下面的课程中进行一致:

public class FooService {

  private Client client;

  public Foo get(Long id) {
    return client.get(id, Foo.class);
  }

  public List<Foo> query() {
    return Arrays.asList(client.get(Foo[].class));
  }

}

除了Foo[].class之外,一切都很好:

public abstract class BaseService<T, I> {

  private Client client;
  private Class<T> type;

  public BaseService(Class<T> type) {
    this.type = type;
  }

  public T get(I id) {
    return client.get(id, type);
  }

  public List<T> query() {
    return Arrays.asList(client.get(/* What to pass here? */));
  }

如果不像Foo[].class那样在构造函数中传递Foo.class,如何解决此问题?

2 个答案:

答案 0 :(得分:4)

Java缺乏直接从元素类获取数组类的工具。一个常见的解决方法是从零长度数组中获取类:

private Class<T> type;
private Class arrType;

public BaseService(Class<T> type) {
    this.type = type;
    arrType = Array.newInstance(type, 0).getClass();
}

您现在可以将arrType传递给client.get(...)方法。

答案 1 :(得分:1)

为什么不做这样的事情:

public class Client<T> {

  T instance;

  T get(long id) {
      return instance;
  }

  List<T> get(){
      return new ArrayList<>();
  }
}

class FooService<T> {

  private Client<T> client;

  public T get(Long id) {
      return client.get(id);
  }

  public List<T> query() {
      return client.get();
  }

}