首先,我對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 {
}
我它可行嗎?我還沒有找到類似於這個需求的例子。
謝謝
你爲什麼要這麼做? – durron597
因爲實際上isAdded,isUpdated和isDeleted的算法總是關於相同的兩個類變量(id和行狀態)。一個MyCustomClass實例代表我的視圖中的一行。每行可以被添加(意味着它必須被持久化),更新,意味着它必須更新現有的記錄),刪除(刪除實體)或沒有(現有的但沒有改變)。這只是儘可能多地重複使用代碼的問題。 –