Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static Map<String, Object> mapObjectValues(Object o){
- Map<String, Object> map=new LinkedHashMap<>();
- mapObjectValues(o, map::put);
- return map;
- }
- @Nullable
- public static String firstToLoverCase(@Nullable String string){
- if(string==null||string.isEmpty()) return string;
- char[] c=string.toCharArray();
- c[0]=Character.toLowerCase(c[0]);
- return new String(c);
- }
- public static void mapObjectValues(Object o, @NotNull BiConsumer<String, Object> push){
- if(o==null) return;
- Class c=o.getClass();
- for(Method m : c.getMethods()){
- if(m.getParameterCount()!=0) continue;
- if(Modifier.isPrivate(m.getModifiers())||Modifier.isProtected(m.getModifiers())||Modifier.isStatic(m.getModifiers())) continue;
- if(m.getReturnType()==Void.TYPE) continue;
- String name=m.getName();
- if(name.length()<=4) continue;
- if(m.getDeclaringClass()==Object.class) continue;
- int prefix;
- if((m.getReturnType()==Boolean.class||m.getReturnType()==boolean.class)&&name.startsWith("is")){
- prefix=2;
- }else{
- if(!name.startsWith("get")) continue;
- prefix=3;
- }
- char ch=name.charAt(prefix);
- if(!Character.isAlphabetic(ch)||!Character.isUpperCase(ch)) continue;
- name=firstToLoverCase(name.substring(prefix));
- try{
- m.setAccessible(true);
- push.accept(name, m.invoke(o));
- }catch(Throwable e){
- push.accept(name, "<read error>");
- }
- }
- for(Field f : c.getFields()){
- if(Modifier.isPrivate(f.getModifiers())||
- Modifier.isProtected(f.getModifiers())||
- Modifier.isStatic(f.getModifiers())||
- Modifier.isTransient(f.getModifiers())) continue;
- String name=f.getName();
- try{
- f.setAccessible(true);
- push.accept(name, f.get(o));
- }catch(ReflectiveOperationException e){
- e.printStackTrace();
- }
- }
- }
- private static void writeRow(Writer output, List<String> names, Function<String, String> getter) throws IOException{
- for(int i=0;i<names.size();i++){
- String value=getter.apply(names.get(i));
- if(value.contains(",")){
- value='"'+value.replace("\"", "\"\"")+'"';
- }
- output.write(value);
- if(i+1<names.size()){
- output.write(',');
- }else{
- output.write('\n');
- }
- }
- }
- public static <T> void writeCsv(Writer output, List<T> data) throws IOException{
- List<String> names=new ArrayList<>();
- mapObjectValues(data.get(0), (name, v)->names.add(name));
- writeRow(output, names, Function.identity());
- for(T t : data){
- Map<String, Object> row=mapObjectValues(t);
- writeRow(output, names, name->{
- Object val=row.get(name);
- return val==null?"":val.toString();
- });
- }
- }
Add Comment
Please, Sign In to add comment