Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting CsvBeanIntrospectionException while using OpenCSV

I'm trying to write a CSV using openCSV 4.1, from a list of beans. However, whenever I run my programme, I get CsvBeanIntrospectionException, and then a NoSuchMethodException: Unknown property 'fieldx' on class 'class TestObject'

I have successfully used the reader counterpart to read a CSV to a list of beans.

Here's my code for the object 'TestObject':

import com.opencsv.bean.CsvBindByName;
import java.io.Serializable;

public class TestObject implements Serializable {
    @CsvBindByName
    int fieldx;
    @CsvBindByName
    int fieldy;
    public TestObject() {
    }
    public TestObject(int x, int y) {
        this.fieldx = x;
        this.fieldy = y;
    }

    public int getX() {
        return fieldx;
    }
    public int getY() {
        return fieldy;
    }
    public void setX(int x) {
        this.fieldx = x;
    }
    public void setY(int y) {
        this.fieldy = y;
    }
    @Override
    public String toString(){
        return "{" + fieldx + "," + fieldy + "}";
    }
}

And here's the rest.

  public class Project {
    public static void main(String[] args) {
        TestObject t1 = new TestObject(1,2);
        TestObject t2 = new TestObject(3,4);

        List<TestObject> testList = new ArrayList<>();
        testList.add(t1);
        testList.add(t2);

        Prep prep = new Prep();
        try {
            prep.writeCSV(testList);
        } catch (IOException | CsvDataTypeMismatchException | CsvRequiredFieldEmptyException ex) {
            ex.printStackTrace();
        }
    }
}

import com.opencsv.bean.*;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.List;

public class Prep {
    public void writeCSV(List<TestObject> t) throws IOException, 
            CsvDataTypeMismatchException,
            CsvRequiredFieldEmptyException {
        Writer writer = new FileWriter("testfile.csv");
     StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).build();
     beanToCsv.write(t);
     writer.close();        
    }
}
like image 748
rothbart Avatar asked Apr 13 '26 10:04

rothbart


1 Answers

I was getting a similar error, try adding a default constructor for the class you want to convert CSV into, it worked for me.

like image 176
Supreet Singh Avatar answered Apr 16 '26 01:04

Supreet Singh



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!