通用使用2个相同的类但来自不同的包

时间:2017-06-01 12:25:56

标签: java generics refactoring

我有两个相同的模型类,但它们位于不同的包中。 第一个是:model.my.prod.Model和第二个model.my.test.Model

我还为此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 个答案:

答案 0 :(得分: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项目结构来避免此类包

答案 1 :(得分:2)

您可以使用Object和显式转换(必要时)

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");
        }
    }
}