WEB开发网
开发学院软件开发Java 利用可重用代码,第 2 部分:捕捉惯用模式 阅读

利用可重用代码,第 2 部分:捕捉惯用模式

 2010-06-24 00:00:00 来源:WEB开发网   
核心提示: 清单 5. MaxLength 属性声明@Retention(RetentionPolicy.RUNTIME)public@interfaceMaxLength{intlength()default0;}MaxLength 验证程序的实际功能存在于两个类中:名为 Validator 的一个抽象类

清单 5. MaxLength 属性声明

@Retention(RetentionPolicy.RUNTIME) 
public @interface MaxLength { 
 int length() default 0; 
} 

MaxLength 验证程序的实际功能存在于两个类中:名为 Validator 的一个抽象类及其具体实现 MaxLengthValidator。Validator 类出现在清单 6 中:

清单 6. 提取基于属性的 Validator 类

public abstract class Validator { 
 
  public void validate(Object obj) throws ValidationException { 
    Class clss = obj.getClass(); 
    for(Method method : clss.getMethods()) 
      if (method.isAnnotationPresent(getAnnotationType())) 
        validateMethod(obj, method, method.getAnnotation(getAnnotationType())); 
  } 
 
  protected abstract Class getAnnotationType(); 
  protected abstract void validateMethod( 
    Object obj, Method method, Annotation annotation); 
}  

该类通过查看 getAnnotationType() 来迭代类中的方法,以确定这些方法是否修饰有特定属性;当它找到一个方法时,就执行 validateMethod() 方法。MaxLengthValidator 类的实现见清单 7:

清单 7. MaxLengthValidator 类

public class MaxLengthValidator extends Validator { 
 
  protected void validateMethod(Object obj, Method method, Annotation annotation) { 
    try { 
      if (method.getName().startsWith("get")) { 
        MaxLength length = (MaxLength)annotation; 
        String value = (String)method.invoke(obj, new Object[0]); 
        if ((value != null) && (length.length() < value.length())) { 
          String string = method.getName() + " is too long." + 
            "Its length is " + value.length() + 
            " but should be no longer than " + length.length(); 
          throw new ValidationException(string); 
        } 
      } 
    } catch (Exception e) { 
      throw new ValidationException(e.getMessage()); 
 
    } 
  } 
 
  @Override 
  protected Class getAnnotationType() { 
    return MaxLength.class; 
  } 
} 

上一页  1 2 3 4 5 6 7 8  下一页

Tags:利用 重用 代码

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接