2017-06-01 31 views
2

我有兩個相同的模型類,但它們在不同的包中。 第一個是:model.my.prod.Model和第二model.my.test.Model2個相同的類,但來自不同的包的通用使用

我也爲這個model.my.prod.Model內搭一件Model類作爲參數的簡單映射:

public class Mapper{ 

    private static Map<Model, String> models= new HashMap<>(); 

    static { 
     models.put(Model.IMAGE_JPG, MediaType.IMAGE_JPEG_VALUE); 
     models.put(Model.IMAGE_GIF, MediaType.IMAGE_GIF_VALUE); 
    } 

    public static String createModelMap(Model model) { 
     if (models.containsKey(model)) { 
      return models.get(model); 
     } else { 
      throw new ModelException("Exeception"); 
     } 
    } 
} 

現在我想用這個Mapper也爲model.my.test.Model,是否有可能沒有此Mapper的副本並更改Model包?

回答

2

可以使用對象和明確的鑄造(必要時)

public class Mapper{ 

    // private static Map<Model, String> models= new HashMap<>();   
    private static Map<Object, String> models= new HashMap<>(); 

    static { 
     models.put(Model.IMAGE_JPG, MediaType.IMAGE_JPEG_VALUE); 
     models.put(Model.IMAGE_GIF, MediaType.IMAGE_GIF_VALUE); 
    } 

    // public static String createModelMap(Model model) { 
    public static String createModelMap(Object model) { 
     if (models.containsKey(model)) { 
      return models.get(model); 
     } else { 
      throw new ModelException("Exeception"); 
     } 
    } 
} 
3

你可以使用全限定類名。它會讓你的代碼變得醜陋,但是你將能夠在Mapper中使用Model類。

所以,與其

public static String createModelMap(Model model) 

,你將會有兩個方法

public static String createModelMap(model.my.prod.Model model) 
    public static String createModelMap(model.my.test.Model model) 

在另外我可以建議你重新命名不同的,更有意義的名字兩類。 而且,也這是一個壞主意,有進行生產和檢驗類的包,你可以使用默認的Maven/gradle這個項目結構,以避免這樣的包

+0

這是一個解決方案,但我認爲它與連接重複的'createModelMap'函數代碼。 – allocer

相關問題