【问题标题】:How is this user defined data type type-casted?这个用户定义的数据类型是如何进行类型转换的?
【发布时间】:2015-05-29 08:49:02
【问题描述】:
Button buttonClick = (Button) findViewById(R.id.button)

应用Java语法,上面的语句表示方法返回的值 findViewById() 更改为数据类型Button,并存储在变量buttonClick中。

我研究过 Java(显然还不够!),但从未遇到过对用户定义的数据类型进行类型转换的情况。 这是如何工作的?

【问题讨论】:

  • 它的工作方式与任何其他铸造相同。谁编写的课程并不重要。
  • 这是可行的,因为 Button 扩展了 View,它是从 findViewById 返回的

标签: java android type-conversion


【解决方案1】:

将@nikis 响应放入代码中:

public class View extends Object {...}
public class Label extends View {...}
public class Button extends View {...}

public View findViewById(String id) {...}

//normal assignment
View v = findViewById(viewID); 

//implicit casting to base class
Object o = findViewById(objectID); 

//compile time error because the return might not be a Button
Button b = findViewById(buttonID);

//explicit cast forces compiler to treat the return as a Button
//if the return is not a Button, then ClassCastException is trown at runtime
Button bb = (Button)findViewById(buttonID);

【讨论】:

    【解决方案2】:

    这是显式转换,因为Button 类扩展了View 类,这是findViewById 方法的返回类型。您应该使用显式转换进行下游转换,因为它不安全。您可以在 Java 中的任何对象之间使用显式转换,但如果这种转换实际上不可能,您将在运行时获得 ClassCastException。另一方面,有隐式转换,它总是安全的,所以不需要声明它。隐式转换是上游转换,例如从ViewObject

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-08
      相关资源
      最近更新 更多