【问题标题】:Downcasting in JavaJava中的向下转型
【发布时间】:2023-03-16 14:59:01
【问题描述】:

在 Java 中允许向上转换,但是向下转换会产生编译错误。

可以通过添加强制转换来消除编译错误,但无论如何都会在运行时中断。

在这种情况下,如果 Java 不能在运行时执行,为什么允许向下转换?
这个概念有什么实际用途吗?

public class demo {
  public static void main(String a[]) {
      B b = (B) new A(); // compiles with the cast, 
                         // but runtime exception - java.lang.ClassCastException
  }
}

class A {
  public void draw() {
    System.out.println("1");
  }

  public void draw1() {
    System.out.println("2");
  }
}

class B extends A {
  public void draw() {
    System.out.println("3");
  }
  public void draw2() {
    System.out.println("4");
  }
}

【问题讨论】:

  • 一个示例 sn-p 的代码加上错误将使这对于那些试图学习这些概念的人来说是一个更好的问题。
  • 我看到上面的例子取自 velocityreviews.com/forums/t151266-downcasting-problem.html 已经有一些很好的答案。
  • @PhiLho - Joel 的主要目的是在一个共同的保护伞下获得所有重要的问题和答案。问题/代码/答案是否已经发布在其他一些网站上并不重要。希望您明白这一点,否则请收听 Joel 的播客。
  • 请编辑此代码,使代码 sn-ps 全部缩进四个空格。这将修复格式。
  • B b = (B) 新 A();是非法的,你不应该称之为沮丧。当我们谈论向上/向下转换时,实际的对象并没有改变,只是什么类型的变量引用了那个对象。不能使用子类型的变量引用基类型的对象。

标签: java casting


【解决方案1】:

当有可能在运行时成功时允许向下转换:

Object o = getSomeObject(),
String s = (String) o; // this is allowed because o could reference a String

在某些情况下这不会成功:

Object o = new Object();
String s = (String) o; // this will fail at runtime, because o doesn't reference a String

当强制转换(例如最后一个)在运行时失败时,将抛出 ClassCastException

在其他情况下它会起作用:

Object o = "a String";
String s = (String) o; // this will work, since o references a String

请注意,有些强制转换在编译时将被禁止,因为它们永远不会成功:

Integer i = getSomeInteger();
String s = (String) i; // the compiler will not allow this, since i can never reference a String.

【讨论】:

  • Object o = new Object(); String s = (String) o; 它对我来说工作正常.. :O 怎么样?
  • @UnKnown:不应该。仔细检查您是否实际编译并运行了该版本,如果您仍然可以重现它,请发布一个单独的问题(使用SSCCE)。
  • @JoachimSauer 你说的那个版本是什么意思?我正在使用 Java 8。
  • @UnKnown:我的意思是你发布的代码不应该运行(它会编译,但在运行时抛出异常)。这些 cmets 不是调试它的空间。请发布一个单独的问题。
  • 如何在运行时强制转换失败?将目标对象引用设置为空?抛出异常?
【解决方案2】:

使用您的示例,您可以这样做:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

【讨论】:

  • 当我的抽象类被多个类扩展时,我刚刚了解到 instanceof 的重要性,我想使用这些类的专有方法,同时引用抽象类类型。不使用 instanceof 我有类转换异常
【解决方案3】:

我相信这适用于所有静态类型语言:

String s = "some string";
Object o = s; // ok
String x = o; // gives compile-time error, o is not neccessarily a string
String x = (String)o; // ok compile-time, but might give a runtime exception if o is not infact a String

类型转换有效地表示:假设这是对转换类的引用并按原样使用它。现在,让我们说 o 真的 是一个整数,假设这是一个字符串没有意义并且会产生意想不到的结果,因此需要进行运行时检查和异常来通知运行时环境某些东西是错了。

在实际使用中,您可以编写代码处理更通用的类,但如果您知道它是什么子类并且需要将其视为子类,则将其转换为子类。一个典型的例子是重写 Object.equals()。假设我们有一个 Car 类:

@Override
boolean equals(Object o) {
    if(!(o instanceof Car)) return false;
    Car other = (Car)o;
    // compare this to other and return
}

【讨论】:

  • 我真的很喜欢这个词,我会编辑你的帖子,让它更明显
【解决方案4】:

我们都可以看到您提供的代码在运行时不起作用。这是因为我们知道表达式 new A() 不能永远B 类型的对象。

但这不是编译器所看到的。当编译器检查是否允许强制转换时,它只会看到:

variable_of_type_B = (B)expression_of_type_A;

正如其他人所证明的那样,这种演员阵容是完全合法的。右边的表达式可以很好地计算为B 类型的对象。编译器看到 AB 具有子类型关系,因此使用代码的“表达式”视图,强制转换可能会起作用。

当编译器确切知道expression_of_type_A 将真正具有什么对象类型时,它不会考虑特殊情况。它只是将静态类型视为A,并认为动态类型可以是AA 的任何后代,包括B

【讨论】:

    【解决方案5】:

    在这种情况下,如果 Java 不能在运行时执行,为什么它允许向下转换?

    我相信这是因为编译器无法在编译时知道强制转换是否成功。对于您的示例,很容易看出演员阵容会失败,但在其他时候并不那么清楚。

    例如,假设类型 B、C 和 D 都扩展了类型 A,然后方法 public A getSomeA() 根据随机生成的数字返回 B、C 或 D 的实例。编译器无法知道此方法将返回哪个确切的运行时类型,因此如果您稍后将结果转换为B,则无法知道转换是否会成功(或失败)。因此编译器必须假设强制转换会成功。

    【讨论】:

      【解决方案6】:

      @原始海报 - 见内联 cmets。

      public class demo 
      {
          public static void main(String a[]) 
          {
              B b = (B) new A(); // compiles with the cast, but runtime exception - java.lang.ClassCastException 
              //- A subclass variable cannot hold a reference to a superclass  variable. so, the above statement will not work.
      
              //For downcast, what you need is a superclass ref containing a subclass object.
              A superClassRef = new B();//just for the sake of illustration
              B subClassRef = (B)superClassRef; // Valid downcast. 
          }
      }
      
      class A 
      {
          public void draw() 
          {
              System.out.println("1");
          }
      
          public void draw1() 
          {
              System.out.println("2");
          }
      }
      
      class B extends A 
      {
          public void draw() 
          {
              System.out.println("3");
          }
      
          public void draw2() 
          {
              System.out.println("4");
          }
      }
      

      【讨论】:

        【解决方案7】:

        向下转换适用于处理向上转换的对象的情况。 向上转型:

        int intValue = 10;
        Object objValue = (Object) intvalue;
        

        所以现在这个objValue 变量总是可以向下转换为int,因为被转换的对象是Integer

        int oldIntValue = (Integer) objValue;
        // can be done 
        

        但是因为objValue 是一个对象,所以它不能转换为String,因为int 不能转换为String

        【讨论】:

          【解决方案8】:

          向下转换在以下代码中非常有用 sn -p 我一直使用它。从而证明向下转换是有用的。

          private static String printAll(LinkedList c)
          {
              Object arr[]=c.toArray();
              String list_string="";
              for(int i=0;i<c.size();i++)
              {
                  String mn=(String)arr[i];
                  list_string+=(mn);
              }
              return list_string;
          }
          

          我将字符串存储在链接列表中。 当我检索链接列表的元素时,会返回对象。要将元素作为字符串(或任何其他类对象)访问,向下转换对我有帮助。

          Java 允许我们编译向下转换的代码,相信我们在做错事。 尽管如此,如果人类犯了错误,它会在运行时被捕获。

          【讨论】:

          • 在 Java 中使用非泛型集合相当于 C++ 中的 void* 指针。在我看来,这根本不是一个好主意。
          【解决方案9】:

          考虑下面的例子

          public class ClastingDemo {
          
          /**
           * @param args
           */
          public static void main(String[] args) {
              AOne obj = new Bone();
              ((Bone) obj).method2();
          }
          }
          
          class AOne {
          public void method1() {
              System.out.println("this is superclass");
          }
          }
          
          
           class Bone extends AOne {
          
          public void method2() {
              System.out.println("this is subclass");
          }
          }
          

          这里我们创建子类 Bone 的对象并将其分配给超类 AOne 引用,现在超类引用不知道 关于子类中的方法method2,即编译期间的Bone。因此我们需要将此超类的引用向下转换为子类引用,以便生成的引用可以知道子类中方法的存在,即Bone

          【讨论】:

          • AOne 看起来有些混乱。请考虑将您的班级名称更改为 Dog 和 Animal 之类的
          【解决方案10】:

          要在 Java 中进行向下转换并避免运行时异常,请参考以下代码:

          if (animal instanceof Dog) {
            Dog dogObject = (Dog) animal;
          }
          

          这里,Animal 是父类,Dog 是子类。
          instanceof 是一个关键字,用于检查引用变量是否包含给定类型的对象引用.

          【讨论】:

            【解决方案11】:

            对象的向下转换是不可能的。 只有

            DownCasting1 _downCasting1 = (DownCasting1)((DownCasting2)downCasting1);
            

            有可能

            class DownCasting0 {
                public int qwe() {
                    System.out.println("DownCasting0");
                    return -0;
                }
            }
            
            class DownCasting1 extends DownCasting0 {
                public int qwe1() {
                    System.out.println("DownCasting1");
                    return -1;
                }
            }
            
            class DownCasting2 extends DownCasting1 {
                public int qwe2() {
                    System.out.println("DownCasting2");
                    return -2;
                }
            }
            
            public class DownCasting {
            
                public static void main(String[] args) {
            
                    try {
                        DownCasting0 downCasting0 = new DownCasting0();
                        DownCasting1 downCasting1 = new DownCasting1();
                        DownCasting2 downCasting2 = new DownCasting2();
            
                        DownCasting0 a1 = (DownCasting0) downCasting2;
                        a1.qwe(); //good
            
                        System.out.println(downCasting0 instanceof  DownCasting2);  //false
                        System.out.println(downCasting1 instanceof  DownCasting2);  //false
                        System.out.println(downCasting0 instanceof  DownCasting1);  //false
            
                        DownCasting2 _downCasting1= (DownCasting2)downCasting1;     //good
                        DownCasting1 __downCasting1 = (DownCasting1)_downCasting1;  //good
                        DownCasting2 a3 = (DownCasting2) downCasting0; // java.lang.ClassCastException
            
                        if(downCasting0 instanceof  DownCasting2){ //false
                            DownCasting2 a2 = (DownCasting2) downCasting0;
                            a2.qwe(); //error
                        }
            
                        byte b1 = 127;
                        short b2 =32_767;
                        int b3 = 2_147_483_647;
            //          long _b4 = 9_223_372_036_854_775_807; //int large number max 2_147_483_647
                        long b4 = 9_223_372_036_854_775_807L;
            //          float _b5 = 3.4e+038; //double default
                        float b5 = 3.4e+038F; //Sufficient for storing 6 to 7 decimal digits
                        double b6 = 1.7e+038;
                        double b7 = 1.7e+038D; //Sufficient for storing 15 decimal digits
            
                        long c1 = b3;
                        int c2 = (int)b4;
            
                        //int       4 bytes     Stores whole numbers from -2_147_483_648 to 2_147_483_647
                        //float     4 bytes     Stores fractional numbers from 3.4e−038 to 3.4e+038. Sufficient for storing 6 to 7 decimal digits
                        float c3 = b3; //logic error
                        double c4 = b4; //logic error
            
            
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
            
            }
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2016-05-08
              • 1970-01-01
              • 1970-01-01
              • 2018-08-07
              • 2013-02-17
              相关资源
              最近更新 更多