Gop*_*opi 17
toString is not specific to android. Its a method in java's Object class, which is the superclass of every java object. 'toString' is meant for returning textual representation of an object. This is generally overridden by java classes to create a human readable string to represent that object.
Apart from many other uses, it is widely used for logging purpose so as to print the object in a readable format. Appending an object with string automatically calls the toString() of that object e.g. "abc" + myObject will invoke 'toString' of myObject and append the returned value to "abc"
A good example of toString implementation would look like -
@Override
public String toString() {
return new StringBuilder()
.append("{Address:")
.append(" street=").append(street)
.append(", pincode=").append(pincode)
.append("}").toString();
}
Run Code Online (Sandbox Code Playgroud)
它和普通的 Java 一样......我用它来调试,如下所示:
class MyClass {
var myVar;
var myOtherVar;
public String toString() {
return "myVar: " + myVar + " | myOtherVar: " + myOtherVar;
}
}
Run Code Online (Sandbox Code Playgroud)
我Log.d("TAG", myClassObject.toString());可以记录我的对象包含的内容...这只是无数可能性之一。
| 归档时间: |
|
| 查看次数: |
15429 次 |
| 最近记录: |