2017-06-01 34 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

相关问题