Is there any way to avoid @SuppressWarnings in this code?

Is there a way to avoid using the @SuppressWarningsbelow and keep the same functionality without warning "Security Type: uncheck AbstractDO [] on E [] ':

public MyClass {
  ...
  private Map<Class<? extends AbstractDO>, AbstractDO[]> map;
  ...
  private void saveConcreteDOs(AbstractDO[] theEntities) {        
    entityMap.put(theEntities[0].getClass(), theEntities);
  }

  @SuppressWarnings("unchecked")
  protected <E extends AbstractDO> E[] getConcreteDOs(Class<E> theType) {
    return (E[]) map.get(theType);
  }
  ...
}

Maybe simplify the announcement of the card?

+3
source share
3 answers

You have a choice: either suppress the warning for the character of your choice will always be successful, or avoid the warning and make sure that the roll succeeds with the try / catch block.

There are only two options.

Maybe there is a way to improve the announcement of the map?

In your case, I would say you have several options.

, throws ClassCastException getConcreteDOs , - , extends AbstractDO. try/catch throws, try/catch .

catch; , @SuppressWarning.

, , .

: , . , - .

+3

, , .

public class MyClass<E extends AbstractDO> {

    private Map<Class<? extends AbstractDO>, E[]> map;

    public void saveConcreteDOs(E[] theEntities) {        
      map.put(theEntities[0].getClass(), theEntities);
    }

    public E[] getConcreteDOs(Class<E> theType) {
      return map.get(theType);
    }
}
+1

-, . .

  private void saveConcreteDOs(AbstractDO[] theEntities) {        
    entityMap.put(theEntities.getClass().getComponentType(), theEntities);
  }

, [0] , . , , , .

, getConcreteDOs() . . , .

, Java. , , , .

:

private Map<Class<? extends AbstractDO>, AbstractDO> map;

protected <E extends AbstractDO> E getConcreteDOs(Class<E> theType) 
{
  AbstractDO obj = map.get(theType);
  return theType.cast(obj);
}

, . Class.cast() , .

, Class<T> T[] castArray(Object[]). , .

Or you can do it, but it's really overly sticky. Do not be afraid of an unverified throw warning if you know what you are doing and have carefully studied your type safety program.

protected <E extends AbstractDO> E[] getConcreteDOs(Class<E[]> arrayType) 
{
  AbstractDO[] array = map.get(arrayType.getComponentType());
  return arrayType.cast(array);
}
...
X[] array = getConcreteDOs(X[].class);
+1
source

Source: https://habr.com/ru/post/1765178/


All Articles