This commit is contained in:
lxyer 2018-12-07 19:13:38 +08:00
parent 26b7123ebc
commit 74aa9781e1

View File

@ -1,11 +1,15 @@
package com.lxyer.excel;
import org.junit.Test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@ -166,4 +170,89 @@ public class ExportKitTest {
response.finish(buf.toString().getBytes());
}
*/
@Test
public void t() {
Object t = new Person();
((Person) t).setAge(20);
((Person) t).setName("'zhangsan'");
Class<?> clazz = t.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
try {
if (field.getType() == String.class) {
field.setAccessible(true);
String v = (String) field.get(t);
v = v.replace("'", "");
field.set(t, v);
System.out.println(field.getName() + "\t|" + field.getType() + "\t|" + v);
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
System.out.println("--------------------------------");
System.out.println(((Person) t).getName());
//Field field = fields[0];
/*
field.getGenericType();
field.setAccessible(true); //暴力反射
Object o = field.get(t);//得到字段数据的值
*/
}
@Test
public void t2() {
Person person = new Person();
/*person.setName("dsafd''s'f");
person.setAge(123);*/
//HashMap<Object, Object> person = new HashMap<>();
//person.put("name", "sdfdsdfad''sa");
dealField(person, (s) -> {
String v = s.replace("'", "");
return v;
});
System.out.println(person.getName());
}
/**
* 对象属性处理
* @param o
* @param function
* @auther lxyer
*/
public void dealField(Object o, Function<String, String> function) {
try {
Class<?> clazz = o.getClass();
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.getType() == String.class) {
field.setAccessible(true);
String v = (String) field.get(o);
//v = v.replace("'", "");
if (v != null) {
v = function.apply(v);
field.set(o, v);
}
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}