Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic and array types, no not what you are thinking (e.g. arrays from generic types)

Tags:

java

generics

I'm trying to specify that a generic class has to be an array, or better yet a primitive array. So far this is what I have got working:

interface Foo<T> {
  void process( T data );
}

public class Moo implements Foo<int[]> {
  void process( int[] data ) {
     // do stuff here
  }
}

This is all perfectly valid Java code and works because primitive arrays extend Object. Note that this question is completely different from all the other Java array generic questions I keep on finding. In that situation people want to create an array out of a generic type.

The problem is that type T can be anything that extends Object. What I want is to do something like:

<T extends ONLY ARRAYS>

or

<T extends ONLY PRIMITIVE ARRAYS>.

Is that possible?

EDIT: The end goal would be to add a compile time check on the array type being passed in. Right now any old object can be passed in and it will compile just fine. The mistake will only be found at runtime when a class cast exception is thrown. In fact this is the whole point of Generics in Java, to add stronger compile time type checking.

like image 747
lessthanoptimal Avatar asked May 02 '12 23:05

lessthanoptimal


Video Answer


1 Answers

You cannot do this. No class can extend an array, so there will never be a type that satisfies the generic parameter T extends Object[]. (Other than Object[] itself, but then you wouldn't be using generics.)

What you could do is something like this:

public interface Foo<T extends Number> {
    public void process(T[] data);
}

But then you might run into performance problems with boxing.

like image 97
Jeffrey Avatar answered Sep 23 '22 23:09

Jeffrey