Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use @SuppressWarning("unchecked") to specific lines of code and not into method level

Tags:

java

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.

like image 395
Rahul Negi Avatar asked Dec 01 '25 08:12

Rahul Negi


1 Answers

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!
}
like image 112
pirho Avatar answered Dec 09 '25 12:12

pirho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!