Java 自定义注释不适用于嵌套对象字段

Java 自定义注释不适用于嵌套对象字段,java,validation,nested,inner-classes,java-annotations,Java,Validation,Nested,Inner Classes,Java Annotations,我已经创建了用于验证的小型自定义注释。如果该字段使用自定义注释进行注释,它将引发异常 下面是代码 import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Ta

我已经创建了用于验证的小型自定义注释。如果该字段使用自定义注释进行注释,它将引发异常

下面是代码

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD})
public @interface NotRequired {
    public boolean value() default true;
}
型号::

public class Profile implements IProfile{
    @NotRequired
    private Integer id; 
    private String fName;    
    private IAddress add;
  //setter and getter

public class Address implements IAddress{
    @NotRequired
    private String address;
测试类别::

public class CustomAnnotationTest {

    public static void main(String[] args) {
        IProfile profile = new Profile();      
        //profile.setId(123);  // in this case it is working fine
        IAddress address= new Address();
        address.setAddress("Aus"); // not working, expected exception should be thrown
        profile.setAdd(address);
        try {
            if (CustomAnnotationNotRequired.validateForNotRequirdField(profile)) {
               System.out.println("Validation Successful");
            }
        } catch (Exception e) {        
            e.printStackTrace();
        }
    }
}
验证器类别:

public class CustomAnnotationNotRequired {
    public static boolean validateForNotRequirdField(Object objectToValidate)
            throws Exception {

        Field[] declaredFields = objectToValidate.getClass().getDeclaredFields();

        for(Field field : declaredFields) {

            Annotation annotation = field.getAnnotation(NotRequired.class);

            if (annotation != null) {

                NotRequired notRequired = (NotRequired) annotation;

                if (notRequired.value()) {
                     field.setAccessible(true); 
                     // annotated field is having value 
                     if (field.get(objectToValidate) != null) {
                         throw new Exception();
                     }
                }
            }
        }
        return true;
    }
}
测试用例: (一)

//对于此输入,将获得正确的结果

(二)


//预期异常。地址类的字段用@NotRequired注释,但没有给出正确的结果。

验证未应用于
地址
字段,因为
validateForNotRequestField
方法仅验证
配置文件
的字段,并且不检查
地址的
@NotRequired
注释。假设
@NotRequired
仅应用于某个公共值类,对
validateForNotRequestField
方法的以下更改将产生所需的结果

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

public class CustomAnnotationNotRequired {
  public static boolean validateForNotRequirdField(Object objectToValidate)
      throws Exception {

    Field[] declaredFields = objectToValidate.getClass().getDeclaredFields();

    for (Field field : declaredFields) {

      Annotation annotation = field.getAnnotation(NotRequired.class);
      if (!isValueClass(field.getType())) {
        field.setAccessible(true);
        if (field.get(objectToValidate) != null) {
          // validate nested field
          validateForNotRequirdField(field.get(objectToValidate));
        }
        continue;
      }
      if (annotation != null) {

        NotRequired notRequired = (NotRequired) annotation;

        if (notRequired.value()) {
          field.setAccessible(true);
          // annotated field is having value
          if (field.get(objectToValidate) != null) {
            throw new Exception();
          }
        }
      }
    }
    return true;
  }

  private static boolean isValueClass(Class<?> fieldType) {
    // Add other class if needed.
    return fieldType.equals(String.class) || fieldType.equals(Integer.class)
           || fieldType.equals(Short.class) || fieldType.equals(Long.class)
           || fieldType.equals(BigDecimal.class)
           || fieldType.equals(Date.class);
  }
}
import java.lang.annotation.annotation;
导入java.lang.reflect.Field;
导入java.math.BigDecimal;
导入java.util.Date;
公共类CustomAnnotationNotRequired{
公共静态布尔ValidateForNotRequestField(对象objectToValidate)
抛出异常{
Field[]declaredFields=objectToValidate.getClass().getDeclaredFields();
for(字段:declaredFields){
Annotation=field.getAnnotation(NotRequired.class);
如果(!isValueClass(field.getType())){
字段。setAccessible(true);
if(field.get(objectToValidate)!=null){
//验证嵌套字段
ValidateForNotRequestField(field.get(objectToValidate));
}
继续;
}
if(注释!=null){
NotRequired NotRequired=(NotRequired)注释;
if(notRequired.value()){
字段。setAccessible(true);
//带注释的字段有值
if(field.get(objectToValidate)!=null){
抛出新异常();
}
}
}
}
返回true;
}
私有静态布尔值isValueClass(类fieldType){
//如果需要,添加其他类。
返回fieldType.equals(String.class)| fieldType.equals(Integer.class)
||fieldType.equals(Short.class)| fieldType.equals(Long.class)
||fieldType.equals(BigDecimal.class)
||fieldType.equals(日期类);
}
}
IProfile profile = new Profile();      
            //profile.setId(123);
            IAddress address= new Address();
            address.setAddress("Aus");
            profile.setAdd(address);  
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.Date;

public class CustomAnnotationNotRequired {
  public static boolean validateForNotRequirdField(Object objectToValidate)
      throws Exception {

    Field[] declaredFields = objectToValidate.getClass().getDeclaredFields();

    for (Field field : declaredFields) {

      Annotation annotation = field.getAnnotation(NotRequired.class);
      if (!isValueClass(field.getType())) {
        field.setAccessible(true);
        if (field.get(objectToValidate) != null) {
          // validate nested field
          validateForNotRequirdField(field.get(objectToValidate));
        }
        continue;
      }
      if (annotation != null) {

        NotRequired notRequired = (NotRequired) annotation;

        if (notRequired.value()) {
          field.setAccessible(true);
          // annotated field is having value
          if (field.get(objectToValidate) != null) {
            throw new Exception();
          }
        }
      }
    }
    return true;
  }

  private static boolean isValueClass(Class<?> fieldType) {
    // Add other class if needed.
    return fieldType.equals(String.class) || fieldType.equals(Integer.class)
           || fieldType.equals(Short.class) || fieldType.equals(Long.class)
           || fieldType.equals(BigDecimal.class)
           || fieldType.equals(Date.class);
  }
}