2

I have a generic method:

public <T> boolean saveRow(T row, Class<T> rowClass) {
    Mapper<T> rowMapper = mappingManager.mapper(rowClass);
    rowMapper.save(row);

    return true;
}

And I would like to ditch the second parameter since I can infer the rowClass from row.getClass().

I've noticed that the only way to make this work is by casting row.getClass() to (Class<T>) row.getClass():

public <T> boolean saveRow(T row) {
    Mapper<T> rowMapper = mappingManager.mapper((Class<T>) row.getClass());
    rowMapper.save(row);

    return true;
}

Why is the cast necessary?

Thanks!

Cristi
  • 117
  • 1
  • 2
  • 9
  • 1
    (BalusC's answer) https://stackoverflow.com/questions/7276096/getclass-of-a-generic-method-parameter-in-a-java –  Jan 13 '17 at 12:33

1 Answers1

1

Because Class.getClass() is not aware of the generic.
Class<?> cannot substitute to Class<T>.

Look at the signature :

public final native Class<?> getClass();
davidxxx
  • 125,838
  • 23
  • 214
  • 215