Search code examples
javagenericsprimitiveprimitive-types

Can someone explain this use of a primitive type in generics in Java?


I'm using the following statement in my Java code and I was surprised to see that it actually compiles:

ResponseEntity<byte[]> responseEntity = restTemplate.getForEntity(url.toString(), byte[].class, params);

The signature for this method from the docs is:

ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> urlVariables)

I was under the impression that you cannot use primitives in generics in Java. If so, how is this working? Is this essentially syntactic sugar for something else that's going on under the hood? My (quite probably wrong) guess is that the compiler converts byte[] to Array and somehow works with that. I was wondering if someone could explain to me how and why this works.


Solution

  • I guess, it's because arrays are actually objects (referenced types) in Java, they are immediate subtypes of Object. So, generics work for them as for any Java reference type.