Domanda

Ho un caso piuttosto semplice in cui faccio un po incarico generico di base:

final Detail detail = field.getAnnotation(Detail.class);
final String example = detail.example();
final Class<?> type = field.getType();
if (List.class.isAssignableFrom(type))
                    ...
else if (Enum.class.isAssignableFrom(type))
    setValue(contract, field, Enum.valueOf(type, example));
else if (...)
.....

ma Enum.valueOf () è un po 'difficile da chiamare, nel mio caso, l'errore è:

  

valueOf (java.lang.Class, java.lang.String) in java.lang.Enum non può essere applicato a (java.lang.Class, java.lang.String)

Questo rende perfettamente senso dal momento che tipo è Class<Object>. Ma dal momento che è Enum CRTP, non riesco a trovare un buon modo per lanciare il tipo di rendere il compilatore felice. Sta usando il tipo grezzo Enum.valueOf((Class)type, example)) l'unica risposta? Mi dà 2 avvertimenti invece di uno solo.

È stato utile?

Soluzione

La seguente riga lo farà con un solo avvertimento:

...
setValue( contract, field, Enum.valueOf( type.asSubclass( Enum.class ), example ) );
...

Altri suggerimenti

È possibile scrivere un metodo di supporto per catturare un tipo "T" che soddisfa il requisito del Enum:

private <T extends Enum<T>> T helper(Class<?> type, String example) {
    return Enum.valueOf((Class<T>)type, example);
}

questo dovrebbe avere un solo avvertimento

e quindi è possibile utilizzarlo come

else if (Enum.class.isAssignableFrom(type))
    setValue(contract, field, helper(type, example));

Edit: Va bene, allora che ne dici:

private <T extends Enum<T>> Object helper(Class<?> type, String example) {
    return Enum.valueOf((Class<T>)type, example);
}

non credo che sia possibile rimuovere gli avvertimenti del compilatore

La migliore delle ipotesi sta riducendo tutti gli errori in una sola come @tangens fa.

Trovato due thread del forum che mostrano risposte senza successo e spiega il motivo per cui un po 'di più.

Così ho messo insieme un esempio completo per dimostrare la questione come la vedo io.

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.List;

public class Test {
  @Retention(RetentionPolicy.RUNTIME)
  @Target(ElementType.FIELD)
  public @interface Detail {
    String example();
  }

  public enum ExampleEnum {
    FOO_BAR, HELLO_WORLD
  }

  @Detail(example = "FOO_BAR")
  public ExampleEnum test;

  public static void main(String[] args) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    populate(new Test());
  }

  public static void populate(Object o) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException {
    final Field field = o.getClass().getField("test");
    final Detail detail = field.getAnnotation(Detail.class);
    System.out.println("Annotation = " + detail);
    final String example = detail.example();
    final Class<?> type = field.getType();
    System.out.println("Field Class = " + type.getName());
    if (List.class.isAssignableFrom(type)) {
    } else if (Enum.class.isAssignableFrom(type)) {
      Class<? extends Enum> enumType = type.asSubclass(Enum.class); // Enum is a raw type. References to generic type Enum<E> should be parameterized
      Enum val = Enum.valueOf(enumType, example); // 1) Enum is a raw type. References to generic type Enum<E> should be parameterized
                                                  // 2) Type safety: Unchecked invocation valueOf(Class<capture#7-of ? extends Enum>, String) of the generic
                                                  //    method valueOf(Class<T>, String) of type Enum
      field.set(o, val);
    }
  }
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top