JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
Java


JAVA.CLASS.CAST : Risky Class Cast (Java)

要旨

A classcast might be incorrect at runtime.

Java checks explicit type downcasts at runtime. If they do not hold, a runtime exception is thrown. This checker verifies that casts will be satisfied at runtime, so that they will never throw an exception.

プロパティ

クラス名 Risky Class Cast (Java)
日本語クラス名 Risky Class Cast (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.CLASS.CAST
カテゴリー
CWE CWE:704 Incorrect Type Conversion or Cast
対応言語 Available for Java and Kotlin.
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Risky Class Cast (Java)"

public class TestCasts {
  private Object f;
  private Object g = "hi";

  public void m1(Object o) {
    if (((String) o).startsWith("hello"))       // "Risky Class Cast (Java)" warning issued here
      System.out.println("nice to meet you");
  }

  public void m2(String s, Object o) {
    if (((String) o).startsWith("hello"))       // "Risky Class Cast (Java)" warning issued here
      System.out.println("nice to meet you");
  }

  public void m3(String s, Object o) {
    if (((String) wrap(o)).startsWith("hello")) // "Risky Class Cast (Java)" warning issued here if JAVA_ANALYSIS_PEDANTIC_MODE=Yes
      System.out.println("nice to meet you");
  }

  public void m4() {
    if (((String) f).startsWith("hello"))       // "Risky Class Cast (Java)" warning issued here if JAVA_ANALYSIS_PEDANTIC_MODE=Yes
      System.out.println("nice to meet you");
  }

  public void m5() {
    if (((String) g).startsWith("hello"))                    // ok: safe cast
      System.out.println("nice to meet you");
  }

  private Object wrap(Object o) {
    return o;
  }

  public void caller1() {
    m1("hi");
    m1(this);
  }

  public void caller2() {
    m2("ciao", "hello");
    m2("come stai", "how are you?");
  }

  public void caller3() {
    m3("ciao", "hello");
    m3("come stai", f = new Object());
  }
}

解決法

For each classcast warning, verify that all types that will ever reach that program point are assignable to the type used for the cast.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。

 

To report problems with this documentation, please visit https://support.codesecure.com/.