Calling method of same name from different class

前端 未结 2 1177
情歌与酒
情歌与酒 2021-01-13 15:32

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

public class People {
    private Long id;
    private String nm;
    private String nmBn;         


        
2条回答
  •  攒了一身酷
    2021-01-13 15:49

    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.

    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.

提交回复
热议问题