来自不同 class 的同名调用方法

Calling method of same name from different class

我有一些 classes 有同名的方法。例如

public class People {
    private Long id;
    private String nm;
    private String nmBn;
    .............
    public Long getId() {
        return id;
    }

    public String getNm() {
        return nm;
    }

    public String getNmBn() {
        return nmBn;
    }
}

public class Company {
    private Long id;
    private String nm;
    private String nmBn;
    .............
    public Long getId() {
        return id;
    }

    public String getNm() {
        return nm;
    }

    public String getNmBn() {
        return nmBn;
    }
}

然后我需要一个像这样工作的方法:

public String getPeopleString(People people) {
    if (people == null) {
        return "";
    }
    return people.getNmBn() + "|" + people.getNm() + "#" + people.getId();
}

public String getCompanyString(Company company) {
    if (company == null) {
        return "";
    }
    return company.getNmBn() + "|" + company.getNm() + "#" + company.getId();
}

所以这些方法在不同类型的对象上做同样的事情。

有没有办法用一种方法做到这一点?

请注意,我无法在 People class 或 Company class 中进行任何更改。

如果 classes 没有实现公共接口或扩展公共基础 class - 即除了名称和签名之外,两组方法之间没有任何关系 - 那么实现这一目标的唯一方法是通过反射。

String getString(Object companyOrPeople) throws InvocationTargetException, IllegalAccessException
{
    if (companyOrPeople == null) {
        return "";
    }
    final Method getNmBn = companyOrPeople.getClass().getDeclaredMethod("getNmBn");
    final String nmBm = getNmBn.invoke(companyOrPeople).toString();
    // same with the other two methods
    return nmBm + "|" + nm + "#" + id;
}

但是,不推荐这样做。您将失去这些方法实际存在的所有编译时保证。没有什么可以阻止某人传递 Integer 或 String 或任何其他没有这些 getter 的类型。

最好的办法是更改现有类型,但如果不能,那就不能。

如果您确实决定更改现有类型,那么请帮自己一个忙,更改属性的名称。因为 nmBn 到底是什么?哦,当然,每个公司都有一个麻木。我真傻。

首先,您应该创建一个具有常用方法的接口,我们称之为Identifiable:

public interface Identifiable {

    Long getId();

    String getNm();

    String getNmBn();
}

理想情况下,你可以让 PeopleCompany 都实现这个接口,但是正如你所说你不能修改现有的 CompanyPeople 类,然后你需要扩展它们,并使 sub类 实现 Identifiable 接口:

public PeopleExtended extends People implements Identifiable { }

public CompanyExtended extends Company implements Identifiable { }

现在,只需将 getCompanyStringgetPeopleString 方法更改为:

public String getIdString(Identifiable id) {
    return id == null ?
           "" :
           id.getNmBn() + "|" + id.getNm() + "#" + id.getId();
}

显然,使用 PeopleExtendedCompanyExtended sub类。