I have a object like this:
public class Person {
String name = "Any";
int age = 9001;
}
public String getName() {return this.name;}
public int getAge() {return this.age;}
Is there a way to print this data with predefined template as stated below?
Person firstOne = new Person();
print_throw_getters("Name: $name%s Age: $age%i",firstOne);
If no, I can convert an Object in the HashMap:
public HashMap getHashMap {
HashMap test = new HashMap<String,Object>();
test.put("name",this.getName());
test.put("age",this.getAge());
return test;
}
Is there a function to print values by keys in predefined template, like this?
print_throw_keys("Name: $name%s Age: $age%i",firstOne.getHashMap());
I do not want to use the indexes like printf("name: $1%s",string) since templates vary considerably, but the incoming object type is unique. .
UPD: Thanks for the answers, but the idea is that there will be a file with a list of templates, which will be inserted into the data, for example:
String template1 = "Your selected Name is $name%s and selected age $age%i";
String template2 = "User: $name%s; Age: $age%i";
Accordingly, the objects themselves will contain a lot more getters.
You can use MapFormat
Example:
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));
Output:
Example: Your selected Name is Mr. X and selected age 21
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With