带有自定义注释的摘要 class

Abstract class with Custom Annotations

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

我想开发一个抽象 class 通过提供基于自定义的通用 implementations/methods 允许我支持各种 POJO 集(value objects 更准确)来自 child class.

的注释

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

例子childclass

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

可行吗?我还没有找到类似这个要求的例子。

谢谢

几乎一切都应该以这种方式工作,但是:

您想对包装对象调用 getter。但是您只将对象的 class 作为参数传递。如果您的方法可行,则必须将对象作为参数提供。

请注意,反射的性能不是很好,尤其是应用于多个对象时。每次将新对象传递给 AbstractValueObject 的构造函数时,您的方法都必须计算它,缓存反射信息(Method、MethodHandle)会使它更快。

如果您知道满足值对象的所有 class 对象(并且您不打算在运行时引入新的 class 对象),那么访问者模式会更合适并且性能更高。