2

I want to generate a parametrized class in Java like

class MyClass<T>

First question: Can T be of type Byte[]?

Second question: If so, how can know I know that it is an array of type Byte? Usually I get the class and then check the class type.

Class typeT = (Class<T>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
anInstance.getClass().equals(typeT)

But how does it work if it is an array?

Thank you in advance

Altober

Altober
  • 956
  • 2
  • 14
  • 28
  • 1
    It should work as expected as arrays are just objects with syntactic sugar in Java (afaik). – Andi Emma Davies Oct 21 '15 at 08:39
  • Ok, thanks a lot and the second question? – Altober Oct 21 '15 at 08:39
  • you could try out the first thing by your own. To the second, this should rather be handelt by generic getter and setter methods. If you are in need to check the type of your array, because you are storing them into a List of Object for example, then you are rather having design flaws. – SomeJavaGuy Oct 21 '15 at 08:41
  • At compile time the compiler will know this due to Type Inference but at runtime it won't be available due to "Type Erasure", Read about them here: https://docs.oracle.com/javase/tutorial/java/generics/erasure.html – Bilbo Baggins Oct 21 '15 at 08:41
  • 1
    You should just be able to use the [`instanceof`](http://stackoverflow.com/questions/7313559/what-is-the-instanceof-operator-used-for) keyword to determine whether it's a `Byte[]` or not. – Andi Emma Davies Oct 21 '15 at 08:41
  • That was fast, thank you all! – Altober Oct 21 '15 at 08:43
  • 1
    @AndyDavies please note that the limitation of `instanceof` is that it will work only against a list of statically defined classes within the codebase. – diginoise Oct 26 '15 at 13:23

1 Answers1

0

Please keep in mind that java.util.ArrayList<Byte> would serve the same purpose with very little storage overhead compared to Byte[], with all operations for arrays available and many more, not to mention dynamic resizing.


If however you have to use Byte[]:

If MyClass<T> is itself a collection, or you can return a single instance of T then the quickest way is to inspect the type of that instance:

list.get(0).getClass().getCanonicalName();

returns java.lang.Byte[].

Also Class<T> which positively tests for arrayism (returns true from Class.isArray()) will return the array's component type. In other words, following code:

list.get(0).getClass().getComponentType();

returns java.lang.Byte.

diginoise
  • 7,352
  • 2
  • 31
  • 39