带自定义注释的抽象类

时间:2015-05-01 18:35:38

标签: java reflection annotations

首先,我对Java反射,泛型和注释都很陌生。

我想开发一个抽象类,它允许我通过提供基于子类的自定义注释的通用实现/方法来支持各种POJO(value objects更准确)。

抽象类

public abstract class AbstractValueObject<T>

    private Class<T> targetClass;
    private Integer id;
    private String rowState;

    public AbstractValueObject(final Class<T> targetClassToSet) {

        this.targetClass = targetClassToSet;

        for (Method method : targetClass.getMethods()) {

            if (method.isAnnotationPresent(ValueObjectId.class)) {
                ... invoke getter that has the @ValueObjectId annotation from the child class, and set that value in the id class attribute...
            }

            if (method.isAnnotationPresent(ValueObjectRowState.class)) {
                ... invoke getter that has the @ValueObjectRowState annotation from the child classfro, and set that value in the rowState class attribute...
            }
        }
    }

    public boolean isNew() {
    ... logic based on id and rowState ...
    }

    public boolean isUpdated() {
    ... logic based on id and rowState ...
    }

    public boolean isDeleted() {
    ... logic based on id and rowState ...
    }

    abstract boolean isValid();
}

示例子类

public class MyCustomClass extends AbstractValueObject<MyCustomClass> implements Serializable {

   private String fileId;
   private String fileRowState;

   @ValueObjectId
   public String getFileId() {
       return fileId;
   }

   public void setFileId(String fileId) {
       this.fileId = fileId;
   }

   @ValueObjectRowState
   public String getFileRowState() {
       return fileRowState
   }

   public void setFileRowState(String fileRowState) {
       this.fileRowState= fileRowState;
   }

   @Override
   public boolean isValid() {
   ...specific implementation...
   }
}

注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValueObjectId {
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ValueObjectRowState {
}

可行吗?我还没有找到任何与此要求相似的例子。

谢谢

0 个答案:

没有答案