CSVと集合オブジェクトのAnnotation操作によるカプセル化


プロジェクトがオンラインになるにつれて、一時的にアイドル状態になるので、暇なうちにチームを連れてこの年のプロジェクトで作った比較的良いコンポーネント、ツールと実践をまとめ、抽出し、私の後続のエッセイで続々と発表します.今日は主に簡単なmavenコンポーネントで、opencsvをAnnotationに基づいて簡単にパッケージ化し、CSVファイルをリスト対像に簡単に変換し、リスト対像をCSVファイルにエクスポートすることができます.
プロジェクト管理アドレスgithubhttps://github.com/greengerong/opencsv-utils.
コードについては言うまでもなく、使い方を簡単に見てみましょう.
Object

package opencsv.utils;


public class Person {


   private int id;


   @Csv("person name")

   private String name;


   @Ignore

   private int age;


   public Person(int id, String name, int age) {

       this.id = id;

       this.name = name;

       this.age = age;

   }


   public Person() {


   }


   public int getId() {

       return id;

   }


   public void setId(int id) {

       this.id = id;

   }


   public String getName() {

       return name;

   }


   public void setName(String name) {

       this.name = name;

   }


   public int getAge() {

       return age;

   }


   public void setAge(int age) {

       this.age = age;

   }

}


  Mapping ignore CSV CSV , @CSV 。

1: CSV:

(1) Annotation

   @Test

   public void shouldGetPersonFromCSV() throws Exception {

       StringReader reader = new StringReader("id,person name
1,name1
2,name2
");

       List personList = personCsvMapper

               .withMapping("id", "id")

               .withMapping("person name", "name")

               .fromCsv(reader);


       assertThat(personList.size(), is(2));


       final Person first = personList.get(0);

       assertThat(first.getId(), is(1));

       assertThat(first.getName(), is("name1"));


       final Person second = personList.get(1);

       assertThat(second.getId(), is(2));

       assertThat(second.getName(), is("name2"));


   }



(2)  

   @Test

   public void shouldToCsv() throws Exception {

       personCsvMapper.withMapping(new CsvColumnMapping(Person.class));

       final ArrayList list = new ArrayList();

       list.add(new Person(1, "name1", 20));

       list.add(new Person(2, "name2", 30));

       final StringWriter writer = new StringWriter();


       personCsvMapper.toCsv(writer, list);


       final String text = writer.toString();

       assertThat(text, is("id,person name
1,name1
2,name2
"));

   }

2: CSV

 @Test

   public void shouldGetPersonFromCsv() throws Exception {

       StringReader reader = new StringReader("id,person name
1,name1
2,name2
");

       List personList = new CsvMapper(Person.class)

               .withMapping(new CsvColumnMapping(Person.class))

               .fromCsv(reader);


       assertThat(personList.size(), is(2));


       final Person first = personList.get(0);

       assertThat(first.getId(), is(1));

       assertThat(first.getName(), is("name1"));


       final Person second = personList.get(1);

       assertThat(second.getId(), is(2));

       assertThat(second.getName(), is("name2"));


   }


  :https://github.com/greengerong/opencsv-utils。 。