Метод, принимающий два разных типа в качестве параметра в Java - PullRequest
0 голосов
/ 25 февраля 2020

Требование : -

В методе getDetails, если передан объект B типа Customclass , то мы вызываем метод getStatus, который принимает Customclass в качестве аргумента. Теперь нам нужно создать аргумент, который может принимать как string / customclass type,

    so if it is string, then we are directly getting the value so need not to call getStatus method
    And if it of type **customclass**, then we need to invoke getStatus

В моем существующем проекте мы вызываем getDetails из разных мест и getDetails - это длинный метод, , поэтому перегрузка слишком дорогая, что приведет к повторению кода

Пожалуйста, предложите другие способы

У меня есть код, похожий на аналогично ниже: -

    getDetails(Strig a, Customclass B) {
      //lengthy calculation long method
      String status = getStatus(B)
     //lengthy calculation long method
   }

Что я хочу сделать, как показано ниже: -

   getDetails(Strig a, Customclass B || String B) {
           //lengthy calculation long method
           String status;
            If(B of type String) {
              status = B;
            } else {

               status = getStatus(B)
            }
           //lengthy calculation long method
   }

Ответы [ 4 ]

0 голосов
/ 25 февраля 2020

Возможна перегрузка без дублирования , путем делегирования вызова от одного к другому:

getDetails(String a, Customclass B) {
    getDetails(a, getStatus(B));
}

getDetails(String a, String status) {
    // just keep this method
}

String getStatus(Customclass object) {
    // I guess you have this one already
} 

Вызов в строке 2 не является рекурсией или чем-то еще, но на самом деле является вызов метода строки 5.

0 голосов
/ 25 февраля 2020

Если я понимаю, что вы хотите сделать, я обычно достигну этого с перегрузкой метода

getDetails(String a, Customclass B) {
    //lengthy calculation long method
    String status = getStatus(B)
    //lengthy calculation long method
}

getDetails(String a, String B) {
    String status = B
}

При перегрузке вы предоставляете 2 или более методов, которые имеют различные требования к параметрам. Затем при вызове метода java определяет, какой метод вызывать, основываясь на типах передаваемых параметров.

0 голосов
/ 25 февраля 2020
interface ICustomInterface {
    //some code if needed
}

class StringWrapper implements ICustomInterface {
    private String value;

    public StringWrapper(String str) {
        this.value = str;
    }

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }
}

public class CustomClass implements ICustomInterface {
    //some code

    public static void getDetails(String a, ICustomInterface b) {
        if (b instanceof CustomClass) {
            System.out.println("Custom class");
            //some code
        } else if (b instanceof StringWrapper) {
            System.out.println(((StringWrapper) b).getValue());
            //some code
        }
    }


    public static void main(String[] args) {
        CustomClass customClass = new CustomClass();
        CustomClass.getDetails("first case", customClass);
        CustomClass.getDetails("second case", new StringWrapper("String"));
    }
}
0 голосов
/ 25 февраля 2020

создать два метода getdetails:

getDetails (строка A, пользовательский класс B)

getDetails (строка A, строка B)

...