在 Udacity 开发 Android 应用程序的初学者类(class)中,他们在初学者类(class)之一中介绍了链接方法的一个简短示例。
这是代码 fragment :
public void submitOrder(View view) {
/**
* Chaining method example given by Udacity.
* stringName variable successfully receives the string value.
*/
EditText inputName = (EditText) findViewById(R.id.name_input);
String stringName = inputName.getText().toString();
/**
* My own example.
* Cannot resolve method 'toString()' error message occurs.
*/
CheckBox checkBox = (CheckBox) findViewById(R.id.check_box);
String hasWhippedCream = checkBox.isChecked().toString();
// What I found by searching on google to make 'toString' work on Boolean
String has = Boolean.toString(checkBox.isChecked());
}
Udacity 的讲师所说的是,为了使链接方法起作用,第一个返回值必须在其类中包含以下方法。
对于上面的例子,她解释说inputName.getText()
返回Editable
对象&它有toString()
方法在其类中,因此此链接方法是有效的,并将在 toString()
上返回字符串。调用它并保存在 stringName 中。
当我尝试在 Boolean
上实现相同格式的链接方法时,我感到困惑。返回。在上面我自己的示例中,我调用 checkBox.isChecked()
,其返回类型 boolean
。现在,Boolean
确实有toString()
根据android文档的方法,所以它应该可以工作,但它不会弹出错误消息。
但是,我在 google 上找到的格式确实有效:
String has = Boolean.toString(checkBox.isChecked())
问题:
- 为什么我的 boolean 返回类型链接方法不起作用?
- 在创建如上所示的链接方法时,是否有一组要遵循的格式规则?为什么
Boolean
具有与inputName.getText()
不同格式的链接方法如上图所示?
最佳答案
Boolean
和 boolean
是 Java 中的不同类型(注意 B)。
Boolean
是一个包装类,它提供了将原始数据类型(本例中为 boolean
)转换为对象以及将对象转换为原始数据类型的机制。
这有效:Boolean.toString(checkBox.isChecked());
因为它使用 boolean 包装类的静态方法 toString
将 isChecked()
方法返回的原始 boolean 值从 checkBox
转换为code> 到 Boolean
对象。
有关包装类的更多信息:
- https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html
- http://www.javatpoint.com/wrapper-class-in-java
简单地说,isChecked()
返回一个原始的 boolean
,它没有任何方法,因此您不能在那里进行方法链接。
关于java - 为什么我的 Java 链式方法尝试不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40015002/