【发布时间】:2018-09-19 22:07:04
【问题描述】:
我有课。我已经覆盖了 toString 值。现在我想将 toString 输出的值映射到类。有什么捷径吗?
public class Cat {
String name;
int age;
String color;
public Cat(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
@Override
public String toString() {
return "Cat{" + "name=" + name + ", age="+age+",color="+color+'}';
}
}`
简而言之,我想将以下值映射到 Cat 类
String value = "Cat{name=Kitty,age=1,color=Black}"
Cat cat = // create a 'Cat'from 'value'
提前谢谢你。
【问题讨论】:
-
你的意思是创建
Cat cat = new Cat("Kitty", 1, "Black");然后打印猫,你就得到了你想要的! -
你不需要做任何额外的事情,重写 toString() 就可以了。
-
“现在我想将 toString 输出的值映射到类” 这对我来说没有任何意义。请问能改一下吗?
-
你说的映射是什么意思?
-
您是否要创建特定的 Cat 实例?即一只一岁的黑猫,名叫凯蒂?或者您希望在调用 toString() 时始终得到相同的结果,而不管实际的属性值如何? (没有多大意义,但是嘿)
标签: java class mapping tostring