vendredi 1 mai 2015

Abstract class with Custom Annotations

First, I am pretty new to Java reflection, generics and annotations.

I would like to develop an abstract class that would allow me to support a various set of POJOs (value objects to be more accurate) by providing generic implementations/methods based on custom annotations from the child class.

Abstract Class

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

Example child class

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

Annotations

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

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

Is it feasible? I haven't found any example similar to this requirement yet.

Thank you





Aucun commentaire:

Enregistrer un commentaire