Generic OR instead of AND

前端 未结 3 2187
时光取名叫无心
时光取名叫无心 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:40

    Is using an anonymous abstract class an option for you? When I need type safe parameters or return types, I use some variant of the code below. That being said, I agree with the other comments here, and am curious what benefit you really derive when you're enforcing a type safety for a group of objects that don't have all that much in common.

    public abstract class Doer {
    
      public void do(T obj) {
        // do some stuff. 
      }
    
    }
    
    // calling method
    
    new Doer(){}.do(new Integer(5));
    

提交回复
热议问题