Pergunta

Alguém sabe como escrever o código abaixo usando genéricos e evitar avisos do compilador? (@Suppresswarnings ("desmarcado") é considerado trapaça).

E, talvez, verificando através de genéricos que o tipo de "esquerda" é o mesmo que o tipo de "certo"?

public void assertLessOrEqual(Comparable left, Comparable right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
Foi útil?

Solução

Isso também funciona com subclasses de tipos comparáveis:

public <T extends Comparable<? super T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || left.compareTo(right) > 0) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

Outras dicas

Que tal agora:

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
  if (left == null || right == null || (left.compareTo(right) > 0)) {
    String msg = "["+left+"] is not less than ["+right+"]";
    throw new RuntimeException("assertLessOrEqual: " + msg);
  }
}

Provavelmente poderia ser feito um pequena um pouco mais geral, mas apenas tornando -o mais complicado também :)

Você não pode, via genéricos, verifique se o tipo de 'esquerda' é o mesmo que o tipo de 'direita' no tempo de execução. Java Generics é implementado via tipo de apagamento, para que as informações sobre os parâmetros de tipo genérico sejam perdidas em tempo de execução.

public <T extends Comparable<T>> void assertLessOrEqual(T left, T right) {
    if (left == null || right == null || (left.compareTo(right) > 0)) {
        String msg = "["+left+"] is not less than ["+right+"]";
        throw new RuntimeException("assertLessOrEqual: " + msg);
    }
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top