业务场景:
导入的时候判断某些必填字段是否已经填上,如果没有填的话,写入该字段必填的信息,并把这些都返回页面展示
使用自定义注解:
定义我们的注解类:如下
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface FiledError {
String value();
}
定义好了注解类之后就可以使用啦,在我们导入的时候如果该字段不能为空的话,我们就添加我们自定义的注解,并写上对应的提示的信息!
@FiledError("【安全事件信息】Excel导入信息有误,名称格式不正确或者不能为空!")
private String name; // 姓名
@FiledError("【安全事件信息】Excel导入信息有误,时间格式不正确或者不能为空!")
private Date date; // 时间
private String remark; //错误信息展示
服务层调用
public UserInfo getFiledError(UserInfo userInfo){
//获取private字段数组
Field[] fs = userInfo.getClass().getDeclaredFields();
try{
for (Field f : fs){
//该字段是否有@FiledError注解
FiledError ef = f.getAnnotation(FiledError.class);
//如果有的话
if (ef != null){
//属性访问设置
f.setAccessible(true);
//获取该字段的值,如果为空的话就设置提示信息
Object val = f.get(userInfo);
System.out.println(ef);
if(StringUtils.isEmpty(String.valueOf(val)) || val == null){//如果为空的话,添加错误信息
userInfo.setRemark(ef.value());
return userInfo;
}
}
}
}catch (Exception e){
}
return userInfo;
}
至此结束!
还是特别好用的,希望能够帮助到大家!有问题及时提出奥!
下面附上我的代码,如果更好的意见,欢迎指出,大家一起成长
package clazz;
/**
* 应用注解 获取提示语句
*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
/**
* 提示的注解
* 反射什么都可以获取得到,很强大的
*/
//注解记得加上@Target @Retention
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@interface Tips{
String value();
}
/**
* 需求
* 这几个字段都不能为空,否则展示在页面上提示信息, 如果实体多了不可能一个一个的判断
*/
class Blog{
@Tips("名称不能为空,且满足条件")
private String name;//名称
@Tips("内容不能为空,且必须大于200字")
private String content;//内容
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
public class Demo1 {
public static void main(String[] args) throws Exception{
Blog blog = new Blog();
blog.setName("");
blog.setContent("123123");
//验证上面的对象是否符合规则
Class<Blog> blogClass = Blog.class;
Field[] declaredFields = blogClass.getDeclaredFields();//获取所有字段
for(Field field:declaredFields){
//判断字段上面是否有注解
Tips annotation = field.getAnnotation(Tips.class);
if(annotation != null){
field.setAccessible(true); //如果不加这个的话,下面获取时会报错的
Class<?> type = field.getType();
//获取当前对象的值
Object o = field.get(blog); //传入对象
if(type == String.class){
if("".equals(o))System.out.println("字段"+field.getName()+"----"+annotation.value());
}
if(type == Integer.class){//自己加入类型
if( o == null)System.out.println("字段"+field.getName()+"----"+annotation.value());
}
}
}
}
}