A Java template that accepts an array; any way to provide this?

I am writing a template class that should take an array as its type.

public class Foo<T> {...}

How best can I ensure that "T" is an array type? (int [], Bar [], ...) Preferably, if possible, it is possible to compile, but otherwise, what is best for debugging time to throw an exception or something if T is not an array?

+3
source share
4 answers

It is not possible to do this exactly as you requested, and for the generic type to indicate an array or primitive.

The syntax allows things like:

public class Foo <az09$_ extends MyClassOrInterface & Serializable & Closeable> {...}

az09 $_ - , .

az09 $_ java, public class Foo<T[]> {...} , public class Foo[] {...}.

, , , T, i.e:

public class Foo<T> {

    public T[] processIt(T... ts) {
        // do something
        return ts;
    } 

}
+2

, , , :

public static boolean isArrayType (Object o) {
    return o.getClass().isArray();
}

, .

+1

. MyClass factory MyClass . , factory MyClass. , , . factory clas ( ), make.

// T is the component type of the array
public class MyClassFactory < T >
{
      // we can't directly enforce TARRAY=T[], but TARRAY=T[]
      public final class MyClass < TARRAY > 
      {
            private MyClass ( ... arguments ) throws ... exceptions { ... code }
            // no non private constructors
            .... more code
      }

      // this is the only way to construct a MyClass
      // so we indirectly enforced TARRAY=T[]
      public MyClass<T[]> make ( ... arguments ) throws ... exceptions 
      {
            return new MyClass <T[]>( ... arguments ) ;
      }
}
+1
source

@emory is on the right track for a clean way to do this without checking the runtime. Personally, I would be interested in the readability of the type name - here is a very compact example using inner classes, and I think the resulting type name at the end is very readable.

public static class Bar {}
public static class Foo<T> {
    public static class Array<TA> {
        private Array() {}
    }
    public Array<T[]> make() {
        return new Array();
    }
}
Foo.Array<Bar[]> fooray = new Foo<Bar>().make();
0
source

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


All Articles