2

I have a function created where i have used @SuppressWarning("unchecked") at method level and it works as expected but i need to move this @SuppressWarning("unchecked") to only those lines of code where the warning is coming in and not at method level:

public static <T> T marshal(Class<T> cls , String xml){
      T res;
      if(cls == xml.getClass()){
          res=(T) xml;--->Need to use @SuppressWarning("unchecked") before this line
      }else{
         JAXBContext ct= JAXBContext.newInstance(cls);
         Unmarshal marshal=ctx.createUnmarshller();
         res=(T)marshal.unmarshal(new StringReader(xml));-->Need to use @SuppressWarning("unchecked") before this line
      }
      return res;
     }

In the above function I have to use @SuppressWarning("unchecked") after if and else because these are the places where warnings are shown.

Rahul Negi
  • 29
  • 2
  • Simply put `@SuppressWarnings("unchecked") final T uncheckedXml = (T) xml;` right before the assignment of `res = uncheckedXml;` for the "true" case, and similar for the second "else" one. – terrorrussia-keeps-killing Dec 17 '20 at 15:08
  • Related (but specific to IntelliJ): https://stackoverflow.com/questions/7798908/disable-warning-in-intellij-for-one-line – Hulk Dec 17 '20 at 15:11

2 Answers2

0

Java annotations can only be placed at certain constructs, which are enumerated in ElementType, which is used when specifying where an annotation can be used (in @Target()). SuppressWarnings specifically is declared with:

@Target({TYPE,FIELD,METHOD,PARAMETER,CONSTRUCTOR,LOCAL_VARIABLE,MODULE})
@Retention(SOURCE)
public @interface SuppressWarnings

Which means it can be placed on one of these declaration contexts. So as @fluffy proposed in the comments, one way to introduce such a context the annotation can be placed at is to introduce a local variable:

@SuppressWarnings("unchecked") 
final T uncheckedXml = (T) xml;

res = uncheckedXml;
Hulk
  • 6,399
  • 1
  • 30
  • 52
0

You could use a generic method to handle @SuppressWarning("unchecked") when appropriate, so defined like:

@SuppressWarnings("unchecked")
public <C> C cast(Object o) {
    return (C) o;
}

However, when you use it and want to have checks you need to check for possible ClassCastException upon assignment (see this). So like:

try {
    res = cast(xml);
} catch (ClassCastException cce) {
    // a bug, help!
}
pirho
  • 11,565
  • 12
  • 43
  • 70