Developus
Developus

Reputation: 1462

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?

Upvotes: 2

Views: 505

Answers (2)

Yuri H
Yuri H

Reputation: 680

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

Upvotes: 2

Volodymyr Demenkov
Volodymyr Demenkov

Reputation: 197

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

Upvotes: 3

Related Questions