Home > other >  Using generics with custom object in method parameters
Using generics with custom object in method parameters

Time:04-05

I have 2 classes as below ::

ItemA {
    // varibales and methods.
}

ItemB{
    // varibales and methods.
}

And I have a method in a service class :

public Map<String, ItemDetails> getItemDetails(Map<String, ItemA> itemMap, String itemType){

    // do something

}

Now I need to pass ItemA or ItemB based upon some conditions in the caller. The return type doesn't change in either case. How I can do that using generics or wild cards.

This is what I am trying to achieve :

public Map<String, ItemDetails> getItemDetails(Map<String, ?> itemMap, String itemType){

    // do something

}

Is the above a good way to handle the scenario or please suggest a better approach. I am new to generics so need your kind help.

CodePudding user response:

I think that a combination of Polymorphism and Generics could be the way to go.

Consider having an interface Item and change your classes correspondingly

interface Item {
    // TODO: declare methods common for all items
}


class ItemA implements Item {
    // TODO: implement the interface
}

class ItemB implements Item {
    // TODO: implement the interface
}

Then your method would become

public Map<String, ItemDetails> getItemDetails(Map<String, Item> items) {
   // TODO: implement the method body
}

But beware writing conditions based on the class types, as it's a common anti pattern

i.e. it's better avoid code like this

// anti pattern, should be avoided
if (item instanceof ItemA) {
    // do one thing
} else if (item instanceof ItemB) {
    // do another thing
}

CodePudding user response:

You could make an interface Item that both ItemA and ItemB implement and define your map as Map<String, Item>, if that would be appropriate for your use case.

  • Related