How to avoid java generics warning

Take the following method, which simply returns a field map 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 the same if you delete the typical typing in the method signature, except that you get a warning for using a raw type. I came across other similar things, especially around reflection, where you don't necessarily have an input type. It seems that reflection will naturally have problems with generics, given that reflection is designed so that you can work with objects when you don't know (or don't care) about the type.

Besides just pasting "@SuppressWarning" into everything, does anyone have any good ideas on a more elegant way to handle reflection without being constantly blamed by generics?

+4
source share
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; } 
+5
source

Effective Java, Chapter 5 (Generics) :

  • Do not use raw types in new code
  • Use common methods

So - do not delete the type parameter.

+4
source

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


All Articles