不同类别的同名调用方法 [英] Calling method of same name from different class

查看:91
本文介绍了不同类别的同名调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些类具有相同名称的方法.例如

I have some classes those have methods with same name. For example

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

然后,我需要一种类似于以下内容的方法:

Then I need a method that works like:

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

因此,这些方法执行相同的操作,但对象类型不同.

So the methods do same thing but on different type of object.

有什么方法可以用一种方法做到这一点吗?

Is there any way to do this with a single method?

请注意,我不能对People类或Company类进行任何更改.

Please note that I can't make any change on People class or in Company class.

推荐答案

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

If the classes do not implement a common interface or extend a common base class - i.e. there is no relationship between the two sets of methods other than the names and signatures - then the only way to accomplish this is via reflection.

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

但是,不建议这样做.您将失去所有这些方法确实存在的编译时保证.没有什么可以阻止某人传递一个整数或一个字符串或任何其他不具有这些吸气剂的类型.

This is not recommended, however. You lose all compile-time guarantees that these methods actually exist. There is nothing to stop someone passing an Integer or a String or any other type which does not have those getters.

最好的办法是更改现有的类型,但是如果不能,则不能.

The best thing to do is to change the existing types but if you can't, you can't.

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

If you do decide to change the existing types then while you're at it do yourself a favour and change the name of the attributes. Because what the hell is a nmBn? Oh, of course, every company has a numbun. How silly of me.

这篇关于不同类别的同名调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆