Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid this java generics warning

Tags:

java

generics

Take the following method, which just returns a map of fields by name:

public static < T > HashMap< String, Field > getFields( Class< T > klass ) {
    HashMap< String, Field > fields = new HashMap< String, Field >();
    for ( Field f : klass.getFields() ) {
        fields.put( f.getName(), f );
    }
    return fields;
}

The method behaves identically if you remove the generic typing in the method signature, except that you get a warning for using a raw type. I've run into other similar things, especially around reflection, where you don't necessarily have the input type. It seems like reflection is just naturally going to have problems with generics, given that reflection is built to let you work with objects when you don't know (or care about) the type.

Aside from just pasting an "@SuppressWarning" on everything, does anyone have any good ideas about more elegant way of handling reflection without being constantly scolded by generics?

like image 523
Steve B. Avatar asked Jan 23 '23 15:01

Steve B.


2 Answers

How about this (you don't need the template parameter T, so you can skip it):

public static HashMap< String, Field > getFields2( Class<?> klass ) {
    HashMap< String, Field > fields = new HashMap< String, Field >();
    for ( Field f : klass.getFields() ) {
        fields.put( f.getName(), f );
    }
    return fields;
}
like image 131
tangens Avatar answered Jan 25 '23 03:01

tangens


Effective Java, Chapter 5 (Generics):

  • Don't use raw types in new code
  • Favor generic methods

So - don't remove the type parameter.

like image 28
Bozho Avatar answered Jan 25 '23 04:01

Bozho