Generifying array type such as Object[].class

Viewed 137

I am trying to generify following class:

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));
  }

}

Everything is alright except 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? */));
  }

How can I solve this issue without passing Foo[].class in the constructor like I have done with Foo.class?

2 Answers

Java lacks facilities to obtain an array class from element class directly. A common work-around is to obtain the class from a zero-length array:

private Class<T> type;
private Class arrType;

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

You can now pass arrType to the client.get(...) method.

Why don't you do something like this:

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();
  }

}
Related