2

lets say i have this interface

public interface HavingName {
    HavingName withName(String name);
    String getName();
}

there are multiple implementations of this interface, each one implementing the factory method withName that returns a new instance of its type, only with the new name.

now i want to write a NameSanitizer that can iterate over a list of concrete HavingName instances and sanitize each name according to some rule

class NameSanitizer {

    public <T extends HavingName> List<T> sanitizeNames(List<T> lines) {
        return FluentIterable.from(lines).transform(new Function<T, T>() {
            @Override
            public T apply(T line) {
                return sanitizeName(line);
            }
        }).toList();
    }

    // TODO: how to avoid this casting warning?
    private <T extends HavingName> T sanitizeName(T line) {
        final String name = line.getName();
        return shouldSanitize(name) ?
                (T) line.withDisplayName(sanitize(name)) : line;
    }
}

i'd love to know if their was any way to avoid the casting warning

jmj
  • 237,923
  • 42
  • 401
  • 438
Asaf David
  • 3,583
  • 3
  • 29
  • 33

0 Answers0