0

I'm trying to conver a java Object to a string separated by "SEPARATOR".

Example

public class Person{

int id;
String name;
String age;
String sex;
}

Main method

Person per = new Person(1, "Kevin", "20", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output

1|Kevin|20|Male

Note that the java object is not a list. And I also want to add a validation so the method ConvertObjectToString can avoid printing object values that are null. ie

Person per = new Person(1, "Kevin", "Male");
String objectAsText = per.ConvertObjectToString(per, "|");

Expected output

1|Kevin|Male

I know that this can be achieved using toString method, but I want to know if there is any other efficient way. Also I don't want to check value by value if null since the java object can be large.

5
  • 1
    What have you tried so far? Commented Jan 6, 2021 at 19:11
  • As mentioned in the question I override the toString method and had concatenated my values. But I think it is not the perfect solution. Commented Jan 6, 2021 at 19:14
  • 3
    There is not likely to be a better solution. Commented Jan 6, 2021 at 19:24
  • Why override toString()? Just make the ConvertObjectToString method do what you want. BTW: if ConvertObjectToString is a member method of Person, it shouldn't take the Person as an argument. Commented Jan 6, 2021 at 19:44
  • Are you trying to create the strings generically, without hard-coding the specific fields? So the ConvertObjectToString method would automatically adapt if more fields were added later? If so, edit your your Question to say so. Your Question is not clear as presently written. Commented Jan 6, 2021 at 20:40

1 Answer 1

1

If you don't want to check each value, I would recommend java object converting into JSON, like into Map<String,Object> and then use Collectors.joining

String value = map.values()
            .stream().filter(Objects::nonNull)
            .map(Object::toString)
            .collect(Collectors.joining("|"));

You can do it using the reflection package, but make sure your fields are public

 Person per = new Person(1, "Kevin", "20", "Male");

   String value = Arrays.stream(Person.getClass().getFields())
           .map(f-> {
               try {
                   return f.get(per).toString();
               } catch (IllegalAccessException e) {
                   e.printStackTrace();
               }
               return null;
           }).filter(Objects::nonNull).collect(Collectors.joining("|"));

    System.out.println(value); //1|Kevin|20|Male
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.