Method receive List of more data types as parameter

1.5k views Asked by At

I have a method and as a parameter I send List. The method looks like this:

public static void setSanctionTypes(List<QueueSueDTO> items) {

    for (QueueSueDTO dto : items) {

        StringBuffer sb = sanctionTypeRutine(dto.getRegres().getDebtors());

        String sanctionType = sb.toString();
        dto.setSanctionType(sanctionType);
    }
}

I need to use this method for different List data types parameters (for example setSanctionTypes(List<QueuePaymentDTO> items); etc.). All clases I want to send as a parameter have method getRegres(), so content of setSanctionTypes() method is common and usable for all these classes I want to send to it.

If I do this

public static void setSanctionTypes(List<?> items) {

    for (Object dto : items) {

        StringBuffer sb = sanctionTypeRutine(dto.getRegres().getDebtors());

        String sanctionType = sb.toString();
        dto.setSanctionType(sanctionType);
    }
}

the dto of type Object doesn't know about getRegres(). I can cast to required type but it will be only one concrete type and it won't be usable for other parameters...

Is there way to resolve my problem ? Thanks.

3

There are 3 answers

1
Tobias On BEST ANSWER

You have do define an interface which forces the classes to implement getRegres(). Then you implement this interface for all classes you need and use:

interface Interface {
  <type> getregres();
}

public static void setSanctionTypes(List<? extends Interface> items) {
0
Vlad On

The all types like QueueSueDTO have to implement a common interface. This way you declare your function as setSanctionTypes(List<? extends QueueDTO> items).

The interface has to contain getRegres and any other functions you find relevant for all your classes, which are used as arguments to the setSanctionTypes:

interface QueueDTO
{
    RegresType getRegres();
    // maybe some more methods
}
0
Royce On

If you have an interface declaring your getRegres() method, and your list entries implement it:

public static void setSanctionTypes(List<? extends YourInterface> items) {

    for (YourInterface dto : items) {

        StringBuffer sb = sanctionTypeRutine(dto.getRegres().getDebtors());

        String sanctionType = sb.toString();
        dto.setSanctionType(sanctionType);
    }
}

For more information on "generics": http://download.oracle.com/javase/tutorial/java/generics/index.html