package com.jareny.java.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Date;
// 设置赋值的数据类型
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SetData {
String setString() default "";
double setDouble() default 0.0;
int setInteger() default 1;
long setLong() default 1L;
}
package com.jareny.java.anno;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 设置日期的数据类型
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface SetDate {
String setString() default "1970-01-01";
}
package com.jareny.java.model;
import com.jareny.java.anno.SetData;
import com.jareny.java.anno.SetDate;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
// 为用户类快速赋值
public class UserInfo {
@SetData(setString="userId")
private String userId;
@SetData(setInteger=30)
private Integer age;
@SetData(setDouble=30000.0)
private Double salary;
@SetData(setLong=5000L)
private Long bath;
@SetDate(setString="1989-01-01")
private String bathDate;
@Override
public String toString() {
return "UserInfo{" +
"userId='" + userId + '\'' +
", age=" + age +
", salary=" + salary +
", bath=" + bath +
", bathDate='" + bathDate + '\'' +
'}';
}
// 为用户类快速赋值
public static List<UserInfo> getUserInfoList() throws Exception {
Class<UserInfo> userInfoClass = UserInfo.class;
Field[] declaredFields = userInfoClass.getDeclaredFields();
List<UserInfo> list = new ArrayList<>();
for (int index=0;index<50;index++){
UserInfo userInfo = userInfoClass.newInstance();
for (Field field:declaredFields){
field.setAccessible(true);
String name = field.getType().getName();
// 判断是否有 @SetData 注解
if(field.isAnnotationPresent(SetData.class)){
// 获取注解
SetData annotation = field.getAnnotation(SetData.class);
// 根据类型赋值操作
if("java.lang.String".equals(name)){
field.set(userInfo,annotation.setString()+index);
}
if("java.lang.Double".equals(name)){
field.set(userInfo,annotation.setDouble()+index);
}
if("java.lang.Integer".equals(name)){
field.set(userInfo,annotation.setInteger()+index);
}
if("java.lang.Long".equals(name)){
field.set(userInfo,annotation.setLong()+index);
}
}
// 判断是否有 @SetDate 注解
if(field.isAnnotationPresent(SetDate.class)){
SetDate annotation = field.getAnnotation(SetDate.class);
if("java.lang.String".equals(name)){
field.set(userInfo,annotation.setString()+index);
}
}
}
System.out.println(userInfo.toString());
list.add(userInfo);
}
return list;
}
public static void main(String[] args) throws Exception {
getUserInfoList();
}
}