Java – avoid isinstance statements
•
Java
How can I refactor this example to avoid the need to check isinstance in each data type? Can I follow any pattern?
public interface GenericData {}
public interface IntegerData extends GenericData{
public Integer Data();
}
public interface StringData extends GenericData{
public String Data();
}
public interface Client {
public boolean LoadData(GenericData data);
}
public class IntegerClientImpl implements Client{
public boolean LoadData(GenericData data){
return IntegerData.class.isinstance(data);
};
}
Solution
You can use generics
public interface Client<Data extends GenericData> {
public boolean LoadData(Data data);
}
public class IntegerClientImpl implements Client<IntegerData> {
@Override
public boolean LoadData(IntegerData data){
// ...
}
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
