Are Suppress Warning Annotations Bad?

Since version 5 of the Java programming language, it is possible to add meta-information in Java programs by means of annotations. In particular some annotations can be used to customise the behaviour of the compiler. For instance the @SuppressWarnings annotation has the purpose of instructing the compiler to suppress a specific warning in the annotated element (and in all program elements contained in the annotated element).

I posit that a free use of @SuppressWarnings by programmers is not a good practice.
Continua a leggere


Using Reflection to (Try to) Overcome Type Erasure Limitations in Java


This week, at the end of a lecture on Java generics I was describing type erasure and its consequences, mainly the fact that the raw type has no information about which type is substituted in the current instance. Consider, for example the following generic class:

class Instantiator<T> {
  public static T newInstance(){
    return new T();

Since after type erasure, any information about T is lost, instantiation of type T is not possible and a Java compiler would issue a compilation error such as Cannot instantiate type T().

For this reason the interface Collection<E>, in the Java Collections framework, defines two methods to convert an the collection into an array:

public Object[] toArray();
public <T> T[] toArray(T[] ary);

The former returns and array of Object,the universal reference type in Java, that does not depend on the actual type T, the latter does not creates and array but accepts it as an argument and merely fills it.

So the question that emerged from the students was: is there a way to find out the actual type parameter used to instantiate a collection class and use it to instantiate an array of the appropriate type?

My first quick answer was: in theory it is possible by means of reflection, but it would be highly inefficient and this is the reason why it was not adopted in the Java collections framework.

The goal of this short article is to elaborate more on that answer and provide further details and evidence.

Continua a leggere