简体   繁体   中英

Generic use of 2 same classes but from different packages

I have two same model classes,but they are in different packages. First one is: model.my.prod.Model and second model.my.test.Model

I have also a simple mapper for this model.my.prod.Model which take a Model class as a parameter:

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

Now I would like to use this Mapper also for model.my.test.Model , is it possible without copy of this Mapper and change a Model package?

You can use full qualified class names. It will make your code ugly, but you will be able to use to Model classes in Mapper.

So, instead of

    public static String createModelMap(Model model) 

you will have two methods

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

In additional I can suggest you to rename both classes with different and more meaningful names. And, also it's a bad idea to have packages for production and testing classes, you can use default maven/gradle project structures to avoid such packages

You can use Object and explicit casting(when necessary)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM