Generic OR instead of AND

前端 未结 3 2182
时光取名叫无心
时光取名叫无心 2020-12-06 08:57

Is it possible to generically parameterize a method accepting EITHER ClassA OR InterfaceB ?

Does Not Compile Due to | Pseudocode

pub         


        
3条回答
  •  旧巷少年郎
    2020-12-06 09:52

    If you really want to do that, you'll need to wrap youur accepted classes inside a custom class of your own. In your example case, probably something like:

    public class OrDoerElement {
        private final Number numberValue;
        private final CharSequence charSequenceValue;
    
        private OrDoerElement(Number number, CharSequence charSequence) {
            this.numberValue = number;
            this.charSequenceValue = charSequence;
        }
    
        public static OrDoerElement fromCharSequence(CharSequence value) {
            return new OrDoerElement(null, value);
        }
    
        public static OrDoerElement fromNumber(Number value) {
            return new OrDoerElement(value, null);
        }
    }
    

    And your orDoer method becomes:

    public void orDoer(OrDoerElement someData) { .... }
    

    Then you can build one of those and use in your method using either:

    orDoer(OrDoerElement.fromCharSequence("a string of chars"));
    orDoer(OrDoerElement.fromNumber(new Integer(6)));
    

    But honestly, that sounds a bit too complex and too much work just to be able to call a method with different parameter types. Are you sure you can't achieve the same using two methods, and a third method for the common logic?

提交回复
热议问题