设计问题 - java - 这样做的最佳方法是什么?

Jay*_*Jay 7 java oop

我有设计问题.

我有两个数据对象,它们是类A和类B的实例.A和B没有任何行为 - 它们是带有getter和setter的java bean.我有一个验证界面和10个实现它定义不同的验证.我想在我的属性文件中指定哪个Validation适用于哪个类.像这样:

类A XYZValidation,ABCValidation

B类:ABCValidation,PPPValidation等

我如何编写我的Validation类,以便它提供作为A类或ClassB实例的对象,或者我将来可能要添加的任何其他C类?

interface Validation {
public boolean check(??);
}
Run Code Online (Sandbox Code Playgroud)

>只是想添加这一行,感谢所有回复此帖的人,并说我喜欢这个神奇的网站上的时间.Stackoverflow岩石!

tpu*_*nen 8

您是否考虑过使用注释来标记要在bean中验证的字段?

如果您有10种不同的验证,则可以指定10个注释.然后使用注释标记字段:

@ValideStringIsCapitalCase
private String myString;

@ValidateIsNegative
private int myInt;
Run Code Online (Sandbox Code Playgroud)

使用反射API遍历所有字段并查看它们是否已标记,如下所示:

public static <T> validateBean(T myBean) throws IllegalAccessException {
    Field[] fields = myBean.getClass().getDeclaredFields();
    // This does not take fields of superclass into account
    if (fields != null) {
        for (Field field : allFields) {
            if (field.isAnnotationPresent(ValideStringIsCapitalCase.class)) {
                field.setAccessible(true);
                Object value = field.get(existingEntity);
                // Validate
                field.setAccessible(false);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

一个选项是使用您要使用的验证器标记整个类.

编辑:记得包含注释:

@Retention(RetentionPolicy.RUNTIME)
Run Code Online (Sandbox Code Playgroud)

为您的注释界面.

EDIT2:请不要直接修改字段(如上例所示).而是使用反射访问他们的getter和setter.