是否可以在未声明的对象上使用 toString?
Is it possible to use toString on undeclared object?
我想为未声明的对象打印“None”值而不是空值。可能吗?
public class class1 {
class2 c2;
public static void main(String[] args) {
class1 c1=new class1();
System.out.println(c1.c2);
}
}
class class2{
public String toString(){
if(this==null){
return "None";
}else{
return "Correct";
}
}
}
编辑:我添加了代码。此代码打印:
null
但我想打印“None”。我该怎么办?
实用程序 class Objects
提供了很多有用的方法。例如 Objects#toString(Object)
和 Objects#toString(Object, String)
.
final String s = Objects.toString(obj, "None");
编辑后:this
引用永远不会为空,因此 this == null
将始终为假。您需要在 class 之外处理 null-check。通常,将对象转换为字符串时会调用 String.valueOf
。此方法处理 null
引用,而不是 class 本身。您必须首先手动将对象转换为字符串(使用上述实用程序)。
您需要更改代码:
public class Class1 {
Class2 c2;
public static void main(String[] args) {
Class1 c1 = new Class1();
System.out.println(Objects.toString(c1.c2, "None"));
}
}
class Class2 {
@Override
public String toString(){
return "Correct";
}
}
您始终可以围绕 Objects#toString(Object,String)
创建一个包装器,以避免一遍又一遍地指定默认值:
public final class MyObjects {
private MyObjects(){}
public static String toString(final Object obj) {
return Objects.toString(obj, "None");
}
}
我想为未声明的对象打印“None”值而不是空值。可能吗?
public class class1 {
class2 c2;
public static void main(String[] args) {
class1 c1=new class1();
System.out.println(c1.c2);
}
}
class class2{
public String toString(){
if(this==null){
return "None";
}else{
return "Correct";
}
}
}
编辑:我添加了代码。此代码打印:
null
但我想打印“None”。我该怎么办?
实用程序 class Objects
提供了很多有用的方法。例如 Objects#toString(Object)
和 Objects#toString(Object, String)
.
final String s = Objects.toString(obj, "None");
编辑后:this
引用永远不会为空,因此 this == null
将始终为假。您需要在 class 之外处理 null-check。通常,将对象转换为字符串时会调用 String.valueOf
。此方法处理 null
引用,而不是 class 本身。您必须首先手动将对象转换为字符串(使用上述实用程序)。
您需要更改代码:
public class Class1 {
Class2 c2;
public static void main(String[] args) {
Class1 c1 = new Class1();
System.out.println(Objects.toString(c1.c2, "None"));
}
}
class Class2 {
@Override
public String toString(){
return "Correct";
}
}
您始终可以围绕 Objects#toString(Object,String)
创建一个包装器,以避免一遍又一遍地指定默认值:
public final class MyObjects {
private MyObjects(){}
public static String toString(final Object obj) {
return Objects.toString(obj, "None");
}
}