2017-03-21 3 views
0

フィールドの名前を取得することはできません。このBeanに格納されていますクラスレベルのアノテーションはジャージー2とJavaを使用して、私はこのようなAPIを持って

@AllOrNone(group="address") 
public final class OrderBean { 

    @Group(name="address") 
    @FormDataParam("address") 
    private String address; 

    @Group(name="address") 
    @FormDataParam("city") 
    private String city; 

    @Group(name="address") 
    @FormDataParam("postcode") 
    private String postcode; 

    // Getters and setters 

} 

私はすべてのフィールドまたはnoneが有効な値が含まれている必要はあり「AllOrNone」と呼ばれる、私が作成したクラスレベルの注釈を、使用していました。 しかし、私は、検証が失敗した場合の応答を構築ExceptionMapperで、私はグループ内のフィールドの名前またはグループの名前についての情報を持っていない:

@Provider 
public class ConstraintViolationMapper implements ExceptionMapper<ConstraintViolationException> { 

    @Override 
    public Response toResponse(ConstraintViolationException e) { 

     // here no clue about the name of the group or the fields involved 
    } 
} 

どのように取得することができます上記のコード内のフィールドの名前またはグループの名前?

EDIT:

ここで私はまた、注釈を作成するために使用されるコードを追加します。

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, 
    ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE}) 
@Retention(RUNTIME) 
@Constraint(validatedBy = AllOrNoneValidator.class) 
@Documented 
public @interface AllOrNone { 
    String message() default "Group of fields should have all fields or none"; 
    Class<?>[] groups() default {}; 
    String group(); 
    Class<? extends Payload>[] payload() default {}; 
} 

そしてここでバリコード:

public final class AllOrNoneValidator extends GroupValidator implements ConstraintValidator<AllOrNone, Object> { 

    private String group; 

    @Override 
    public void initialize(final AllOrNone constraintAnnotation) { 

    this.group = constraintAnnotation.group(); 
    } 

    @Override 
    public boolean isValid(final Object bean, final ConstraintValidatorContext constraintValidatorContext) { 

    // some code here 
    } 
} 

答えて

0

以下はトリックを行う必要があります。

Set<ConstraintViolation> violations = e.getConstraintViolations(); 

for (ConstraintViolation violation : violations) { 
    String property = violation.getPropertyPath().getName(); 
} 
+0

私は試しましたが、それはretu rns "doOrder.arg0"。本当に便利なものはありません。私はグループの名またはグループに属するフィールドの名前を知る必要があります。 – user1883212

+0

@ user1883212 Java 8を使用している場合は、パラメータ名でコンパイルしてみてください。 –

+0

が "-parameters"でコンパイルしようとしましたが、同じままです。 – user1883212

関連する問題