全部代码如下,问题在第一个代码片中
package ref;
import java.lang.reflect.Field;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import ref.annotation.ExcelField;
import ref.model.Emp;
//测试类
public class Test {
public static void main(String[] args) throws Exception {
outExcel(initData());
}
//利用反射输出数据
public static <T> void outExcel(List<T> list) throws Exception{
Field[] declaredFields = list.get(0).getClass().getDeclaredFields();
for (Field field : declaredFields) {
ExcelField annotation = field.getAnnotation(ExcelField.class);
System.out.println(annotation.key());
}
/*
* =======================================
* ================问题如下===============
* =======================================
*/
/*
* 这里有几个地方,我没看懂
* 1、<T>这是个泛型,泛型一般不都是定义在类后面吗?泛型定义在方法上会不会不好?
* 2、下面的没看懂代码片中
*/
for(int i=0;i<list.size();i++){
/*------------没看懂代码片-开始--------------*/
//这个获取的是Emp类型
T t = list.get(i);
//这个是Emp的属性数组
Field[] fields = t.getClass().getFields();
for (Field field : fields) {
//field这是属性
//field.get(t) 这句话我就不理解了
//为什么属性获取Emp类,可以获取到属性的值
Object object = field.get(t);
/*------------没看懂代码片-结束--------------*/
if(object instanceof Integer) System.out.println((Integer)object);
if(object instanceof String) System.out.println((String)object);
if(object instanceof Timestamp) System.out.println((Timestamp)object);
}
}
}
//构造数据
private static List<Emp> initData() {
List<Emp> emps = new ArrayList<Emp>();
Emp emp;
for(int i=0;i<3;i++){
emp = new Emp(i,UUID.randomUUID().toString(),new Timestamp(System.currentTimeMillis()));
emps.add(emp);
}
return emps;
}
}
package ref.model;
import java.sql.Timestamp;
import ref.annotation.ExcelField;
public class Emp {
@ExcelField(key = "编号")
public Integer id;
@ExcelField(key = "名字")
public String name;
@ExcelField(key = "创建时间")
public Timestamp createTime;
public Emp(Integer id, String name, Timestamp createTime) {
super();
this.id = id;
this.name = name;
this.createTime = createTime;
}
}
package ref.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//@Target,约束之用,告诉计算机,此注解可以被放在哪些元素之前
@Target({
ElementType.FIELD,
ElementType.METHOD
})
//@Retention,告诉计算机,此注解的生命周期
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelField {
String key();
}