我正在尝试编写使用Comparator
的通用Function
来获取基于propertyName
的值进行比较,并希望避免在几个地方进行投射。
以下是我希望避免使用强制转换的代码和地点:
public class Catalog {
private Integer id = null;
private String name = null;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Catalog withId(Integer id){
setId(id);
return this;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Catalog withName(String name){
setName(name);
return this;
}
}
private < U extends Comparable<? super U> > Optional< Comparator<Catalog> > createComparator(String property, boolean ignoreCase){
Optional< Function<Catalog, U > > keyExtractor = getKeyExtractor(property, ignoreCase);
if ( !keyExtractor.isPresent() ) return Optional.empty();
return Optional.of( Comparator.comparing( keyExtractor.get() ) );
}
private < U extends Comparable<? super U> > Optional< Function< Catalog, U > > getKeyExtractor(String property, boolean ignoreCase){
Optional< Function<Catalog, U > > keyExtractor = getKeyExtractor(property);
if ( !keyExtractor.isPresent() ) return Optional.empty();
return Optional.of( c -> {
if (c == null) return null;
U value = keyExtractor.get().apply(c);
if (value instanceof String) return ignoreCase ? (U)( (String)value ).toLowerCase() : value; //NEED TO AVOID CASTING
return value;
} );
}
private < U extends Comparable<? super U> > Optional< Function< Catalog, U > > getKeyExtractor(String property){
if ( "id".equalsIgnoreCase(property) ) return Optional.of( (c) -> (U)c.getId() ); //NEED TO AVOID CASTING
else if ( "name".equalsIgnoreCase(property) ) return Optional.of( (c) -> (U)c.getName() ); //NEED TO AVOID CASTING
else return Optional.empty();
}