我有一个这样的对象:
public class Person {
String name = "Any";
int age = 9001;
}
public String getName() {return this.name;}
public int getAge() {return this.age;}
有没有办法使用如下所述的预定义模板打印此数据?
Person firstOne = new Person();
print_throw_getters("Name: $name%s Age: $age%i",firstOne);
如果不是,我可以在 HashMap 中转换一个对象:
public HashMap getHashMap {
HashMap test = new HashMap<String,Object>();
test.put("name",this.getName());
test.put("age",this.getAge());
return test;
}
是否有像这样在预定义模板中通过键打印值的功能?
print_throw_keys("Name: $name%s Age: $age%i",firstOne.getHashMap());
我不想使用像 printf("name: $1%s",string) 这样的索引,因为模板差异很大,但传入的对象类型是唯一的。 .
UPD:感谢您的回答,但我们的想法是会有一个包含模板列表的文件,该文件将被插入到数据中,例如:
String template1 = "Your selected Name is $name%s and selected age $age%i";
String template2 = "User: $name%s; Age: $age%i";
相应地,对象本身将包含更多的 getter。
最佳答案
你可以使用 MapFormat
例子:
String text = "Your selected Name is {name} and selected age {age}";
HashMap test = new HashMap();
test.put("name", "Mr. X");
test.put("age", "21");
System.out.println("Example: " + MapFormat.format(text, test));
输出:
示例:您选择的姓名为 X 先生,年龄为 21 岁
关于java - 通过 getters/keys 从 Object/Hashmap 打印数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17340065/