Generating an array type, such as Object []. Class

I am trying to create the 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 fine 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 problem without passing Foo[].class in the constructor, as I did with Foo.class ?

+5
source share
2 answers

In Java, there is no way to get an array class from an element class directly. A common task is to get a class from an array of zero length:

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

Now you can pass arrType to the client.get(...) method.

+4
source

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

Source: https://habr.com/ru/post/1272006/


All Articles