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
?
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.
No, we cannot create an array of generic type objects if you try to do so, a compile time error is generated.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With