1

I have got an array of Classes, declared as follows:

Class<?>[] serviceStack = {GetPlanningData.class, GetTimeTable.class, GetDataToSync.class, GetData.class};

Classes GetPlanningData, GetTimeTable, GetDataToSync and GetData are all subclasses of IntentService.

Can I declare an array of subclasses of IntentService? I tried:

Class<? extends IntentService>[] serviceStack;

and

Class<IntentService>[] serviceStack;

but the first one is a "Generic array creation", as Android Studio says, and the second one permits only to create {IntentService.class, IntentService.class, ...} and no subclasses are allowed.

EDIT: I am programming in Android, and the main goal of this is to call Services sequantially. So I put this array as an extra of the first Service and when the service has finished I call the first element of the array, passing the array without the first element.

This works, but I can't use Lists because I can't put a List extra to a Context.

3
  • I would work around the issue and create a generic collection instead. Something in the lines of List<? extends IntentService>. Commented Aug 31, 2015 at 10:26
  • what is your problem? Commented Aug 31, 2015 at 10:27
  • I have to call a series of IntentService sequentially, but I can't use a List (that'd be great) because, programming on Android, I can't put a List "extra". Commented Sep 4, 2015 at 9:46

2 Answers 2

2

Do not use array. Create a List instead:

List<Class<? extends IntentService>> serviceStack = Arrays.asList(
    GetPlanningData.class, GetTimeTable.class, 
    GetDataToSync.class, GetData.class);

This way you will be type-safe.

Sign up to request clarification or add additional context in comments.

1 Comment

That would be great, but I can't use Collections, because programming on Android I have to put this array in an extra, and I can't put a list in a extra.
2

I think this answers your question:

You cannot create arrays of parameterized types

source:

https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createArrays

1 Comment

That is unfortunately not strictly true: to be precise you cannot directly instantiate arrays of non-reifiable types. You can therefore instantiate an array like new Foo<?>[1] as it is reifiable (the only reifiable parameterized type is an unbounded wildcard parameterized type).

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.