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

我创建了小的自定义注释,用于验证。如果使用自定义注释对字段进行注释,则会引发异常。

下面是代码

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();
        }
    }
}

ValidatorClass:

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;
    }
}

测试用例:   1)

 IProfile profile = new Profile();     
        profile.setId(123); 

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

2)

IProfile profile = new Profile();      
            //profile.setId(123);
            IAddress address= new Address();
            address.setaddress("Aus");
            profile.setadd(address);  

//预期的异常。Address类的字段使用@NotRequired注释进行注释,但未给出正确的结果。

sjmissys 回答:自定义注释不适用于嵌套对象字段

该验证不适用于address字段,因为validateForNotRequirdField方法仅验证profile的字段,而不检查{{的@NotRequired}批注1}}。假设Address仅应用于某些公共值类,对@NotRequired方法的以下更改将产生所需的结果。

validateForNotRequirdField
本文链接:https://www.f2er.com/3080335.html

大家都在问