Search code examples
javagenericsgeneric-method

Why do Java Generic Method Argument Classes Need to be Cast


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!


Solution

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

    Look at the signature :

    public final native Class<?> getClass();