2

I'm attempting to convert the following method:

public List<AliasIp> getStoreAsList(String storeName) {
    return new java.util.ArrayList<>(Arrays.asList(mGson.fromJson(getStoreRaw(storeName), AliasIp[].class)));
}

To a generic version similar to:

public <T> List<T> getStoreAsList(String storeName) {
    return new java.util.ArrayList<T>(Arrays.asList(mGson.fromJson(getStoreRaw(storeName), T[].class)));
}

But I'm running into troubles with the T[].class which doesn't compile with the error:

"Cannot select from a type variable"

What should the syntax be to avoid that error?

8
  • 1
    You face the "type erasure" of Java. Take a look at stackoverflow.com/questions/529085/…, it's not 100% equal to your uestion, but in the answer to this question you can read why compiler can't understand what T[].class is. Commented Feb 7, 2016 at 10:43
  • 1
    When Java process you code, it is always remove T expression with definite class (type erasure). Java never leaves T as is. So, when it comes across T[], it has no idea, what class should be here. I suggest you follow solution of @Kolesnikovich Dmitry, and pass class as method parameter. Commented Feb 7, 2016 at 10:57
  • By the way Arrays.asList already returns a list. There is no need to copy it into an ArrayList, unless the method guarantees to return the specific type ArrayList, which is not recognizable from its current signature. Commented Feb 7, 2016 at 10:58
  • @Holger the reason for the redundant ArrayList is Arrays.asList is a wrapper around an array and does not allow list.Add() type functionality. See stackoverflow.com/questions/1624144/… Commented Feb 7, 2016 at 15:05
  • @KenBekov After reading angelikalanger.com/GenericsFAQ/FAQSections/… I imagine that T is removed during Type erasure as T is used as a Type argument. So that T[].class becomes [].class, which is clearly not a statement. Am I understanding the process correctly? Commented Feb 7, 2016 at 16:14

1 Answer 1

7

You can include Class<T[]> klass into method parameters like this:

public <T> List<T> getStoreAsList(String storeName, Class<T[]> klass) {
    return new java.util.ArrayList<T>(Arrays.asList(mGson.fromJson(getStoreRaw(storeName), klass)));
}

Then just use it like this:

List<MyStore1> myStores1 = getStoreAsList("myStoreName1", MyStore1[].class);
List<MyStore2> myStores2 = getStoreAsList("myStoreName2", MyStore2[].class);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.