How to 'wrap' two classes with identical methods?

前端 未结 6 941
误落风尘
误落风尘 2021-02-15 10:52

I have to handle two classes with identical methods but they don\'t implement the same interface, nor do they extend the same superclass. I\'m not able / not allowed to change t

6条回答
  •  醉梦人生
    2021-02-15 11:47

    i think your original wrapper class is the most viable option...however it can be done using reflection, your real problem is that the application is a mess...and reflection is might not be the method you are looking for

    i've another proposal, which might be help: create a wrapper class which has specific functions for every type of classes...it mostly copypaste, but it forces you to use the typed thing as a parameter

    class X{
        public  int asd() {return 0;}
    }
    class Y{
        public  int asd() {return 1;}
    }
    class H{
        public  int asd(X a){
            return  a.asd();
            }
        public  int asd(Y a){
            return  a.asd();
            }
    }
    

    usage:

    System.out.println("asd"+h.asd(x));
    System.out.println("asd"+h.asd(y));
    

    i would like to note that an interface can be implemented by the ancestor too, if you are creating these classes - but just can't modify it's source, then you can still overload them from outside:

    public  interface II{
        public  int asd();
    }
    class XI extends X implements II{
    }
    class YI extends Y implements II{
    }
    

    usage:

    II  a=new XI();
    System.out.println("asd"+a.asd());
    

提交回复
热议问题