簡體   English   中英

Java通用實用程序方法在兩種類型之間進行轉換

[英]Java generic utility method to convert between two types

我有一個方法來轉換兩個不同類的對象。 這些是DTO對象和hibernate實體類。

public static DomainObject1 convertToDomain(PersistedObject1 pObj) {
        if (pObj == null)
          return null;
        DomainObject1 dObj = new DomainObject1();
        BeanUtils.copyProperties(pObj,dObj); //Copy the property values of the given source bean into the target bean.
        return dObj;
      }

而不是使用與DomainObject2PersistedObject2等相同的方法。 是否可以使用具有以下簽名的通用方法? (無需傳遞源類和目標類)

 public static<U,V> U convertToDomain(V pObj) {
    ...}

PS :( 另一個主題是,當實體具有相同的結構時,使用DTO是浪費的,盡管有hibernate文檔和其他來源,有些人不同意)

要實現此目的,您需要傳遞要查找的Domain對象的類。 像下面這樣的東西會起作用:

public static <T> T convert(Object source, Class<T> targetType)
        throws InstantiationException,
        IllegalAccessException,
        InvocationTargetException {
    if (source == null)
        return null;
    T target = targetType.newInstance();
    BeanUtils.copyProperties(source, target);
    return target;
}

說到這一點,就像看起來一樣,你已經在使用Spring了。 您可以嘗試使用Spring的ConversionService (自動線路轉換服務)注冊一個特殊的轉換器,您可以使用convert方法來實現相同的結果)。

請注意,您應該添加一些檢查以確保每個實體和域對象都是兼容的,否則您最終會遇到大問題而且您的代碼容易出錯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM