com.github.skjolber.stcsv.databinder.DefaultStaticCsvMapper Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of databinder Show documentation
Show all versions of databinder Show documentation
High-performance CSV databinding library
package com.github.skjolber.stcsv.databinder;
import java.io.Reader;
import java.lang.reflect.Constructor;
import com.github.skjolber.stcsv.AbstractCsvReader;
import com.github.skjolber.stcsv.EmptyCsvReader;
/**
*
* Static CSV parser generator - for specific parser implementation
*
* Thread-safe.
* @param csv line output value
*/
public class DefaultStaticCsvMapper implements StaticCsvMapper {
// https://stackoverflow.com/questions/28030465/performance-of-invoking-constructor-by-reflection
private final Constructor extends AbstractCsvReader> readerConstructor;
private final Constructor extends AbstractCsvReader> readerArrayConstructor;
public DefaultStaticCsvMapper(Class extends AbstractCsvReader> cls) throws Exception {
if(cls != null) {
this.readerConstructor = cls.getConstructor(Reader.class);
this.readerArrayConstructor = cls.getConstructor(Reader.class, char[].class, int.class, int.class);
} else {
this.readerConstructor = null;
this.readerArrayConstructor = null;
}
}
public AbstractCsvReader newInstance(Reader reader) {
try {
if(readerArrayConstructor != null) {
return readerConstructor.newInstance(reader);
}
return new EmptyCsvReader<>();
} catch (Exception e) {
throw new RuntimeException(e); // should never happen
}
}
public AbstractCsvReader newInstance(Reader reader, char[] current, int offset, int length) {
try {
if(readerArrayConstructor != null) {
return readerArrayConstructor.newInstance(reader, current, offset, length);
}
return new EmptyCsvReader<>();
} catch (Exception e) {
throw new RuntimeException(e); // should never happen
}
}
/*
public AbstractCsvClassFactory newInstance(Reader reader, boolean skipHeader) throws IOException {
if(skipHeader) {
do {
int read = reader.read();
if(read == -1) {
return new NullCsvClassFactory();
}
if(read == (int)'\n') {
break;
}
} while(true);
}
try {
return constructor.newInstance(reader);
} catch (Exception e) {
throw new RuntimeException(); // should never happen
}
}
*/
}