Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing data from Object/Hashmap by getters/keys

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.

like image 348
arkhamvm Avatar asked Sep 08 '26 04:09

arkhamvm


1 Answers

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

like image 150
PraK Avatar answered Sep 10 '26 19:09

PraK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!