1

I'd like to generate a CSV file from a list of custom objects.

I have an abstract class:

public abstract class MyClass{
    public static final String SEPARATOR = ";";

    // many private variables

    @Override
    public String toString(){
        // return all my variables values separated by SEPARATOR
    }
}

and several concrete classes that inherit from this class. I'd like to implment the toString() method only in this class, without re-implement in each concrete class.

Is there any useful library to acheve this or do I have to implement manually toString() method for each class? Should I use reflection?

2

3 Answers 3

2

There is a library similar to your requirements by the name of opencsv

Sign up to request clarification or add additional context in comments.

Comments

1

Use OpenCSV. It's a library for parsing and writing CSV files, that handles quotes, different separators and multi-line values.

Comments

1

The problem with a reflection approach would be 1) You easily get fields in your concrete classes that you don't want in your csv table. 2) how do you generate a header for your csv table?

Also, i find it bad design to put the csv generation logic inside of your custom objects, of course depending on what they represent (there may also be reasons in favor of your approach, no doubt). Consider using a seperate class for that.

Yes, you can (must even) use reflection, no i don't know whether there already exists a library that handles this for you. OpenCSV as mentioned by others can do the job of putting everything together once you have the values you want in your CSV table.

Take a look at Class.getFields(), Field.setAccessible() (if you need that), that should do. It's actually not that hard to use reflection.

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.