简体   繁体   English

Findbugs BC_UNCONFIRMED_CAST警告

[英]Findbugs BC_UNCONFIRMED_CAST warning

I have two classes - 我有两节课 -

class A {}
class B extends A {}

And I was doing this - 而我这样做 -

A a = new B();
if(a instanceof B){
   doSomething((B) a); // type case a to B
}

doSomething method looks like this - doSomething方法看起来像这样 -

public void doSomething(B b) { .. }

Findbugs raised no warning in above code. Findbugs在上面的代码中没有提出警告。 But if I change the above code like this - 但如果我改变上面这样的代码 -

class A {
   public boolean isOfTypeB() {
      return this instanceof B;
   }
}
class B extends A {}

A a = new B();
if(a.isOfTypeB()){
  doSomething((B) a); // BC_UNCONFIRMED_CAST warning
}

Findbugs raises an error BC_UNCONFIRMED_CAST. Findbugs引发错误BC_UNCONFIRMED_CAST。 I don't see much difference in both the implementations. 我认为两种实现都没有太大区别。 Any suggestions, am I missing anything? 有什么建议吗,我错过了什么吗?

FindBugs looks for the instanceof prior to checkcast bytecode. FindBugs在checkcast字节码之前查找instanceof You can use an assert to please the FindBugs warning and future maintainers of your code. 您可以使用assert取悦FindBugs警告以及​​代码的未来维护者。

A a = new B();
if (a.isOfTypeB()){
  assert a instanceof B : a.getClass(); //Safe to call getClass because 'a' is non-null.
  doSomething((B) a);
}

Prior to FindBugs 3.0 you could use dynamic cast to work around this warning. 在FindBugs 3.0之前,您可以使用动态强制转换来解决此警告。 Don't do this as it is detected in later versions of FindBugs. 不要这样做,因为在FindBugs的更高版本中检测到它。

 
 
 
  
  A a = new B(); if (a.isOfTypeB()) { doSomething(B.class.cast(a)); }
 
  

One of the things to consider is that FindBugs detects patterns that do create actual bugs and patterns that can create actual bugs. 需要考虑的一件事是,FindBugs检测到的模式确实会产生可能产生实际错误的实际错误和模式。 The 'instanceof' keyword and Class.cast behavior can't be overridden but 'isTypeOfB' can be overridden. 无法覆盖'instanceof'关键字和Class.cast行为,但可以覆盖'isTypeOfB'。 Even if FindBugs doesn't detect that both examples of your code and mine function as expected, maybe the warning is correct on the grounds that it is advisable to not do this. 即使FindBugs没有检测到您的代码和我的两个示例都按预期运行,也许警告是正确的,理由是不建议这样做。

For those who look for casting ServletResponse to HttpServletResponse, Use instanceof as below. 对于那些寻找将ServletResponse转换为HttpServletResponse的人,请使用如下的instanceof

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {       

        if (response instanceof HttpServletResponse)
            noCaching((HttpServletResponse) response);

        chain.doFilter(request, response);
    }

BC_UNCONFIRMED_CAST bug will not be reported in findbugs report. findbugs报告中不会报告BC_UNCONFIRMED_CAST错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM