Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generifying array type such as Object[].class

Tags:

java

generics

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?

like image 873
s.alem Avatar asked Sep 21 '17 10:09

s.alem


People also ask

Is array a class or interface?

Although an array type is not a class, the Class object of every array acts as if: The direct superclass of every array type is Object . Every array type implements the interfaces Cloneable and java. io.

Can you create an array of generic type?

No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.

Can we have generic array in Java?

Java allows generic classes, methods, etc. that can be declared independent of types. However, Java does not allow the array to be generic. The reason for this is that in Java, arrays contain information related to their components and this information is used to allocate memory at runtime.

Why does Java not allow generic arrays?

If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.


1 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.

like image 158
Sergey Kalinichenko Avatar answered Oct 22 '22 01:10

Sergey Kalinichenko