returning a Void object

前端 未结 5 1260
故里飘歌
故里飘歌 2020-12-09 00:17

What is the correct way to return a Void type, when it isn\'t a primitive? Eg. I currently use null as below.

interface B{ E method();          


        
5条回答
  •  庸人自扰
    2020-12-09 01:13

    Just for the sake of it, there is of course the possibility to create Void instance using reflection:

    interface B{ E method(); }
    
    class A implements B{
    
        public Void method(){
            // do something
    
            try {
                Constructor voidConstructor = Void.class.getDeclaredConstructor();
                voidConstructor.setAccessible(true);
                return voidConstructor.newInstance();
            } catch (Exception ex) {
                // Rethrow, or return null, or whatever.
            }
        }
    }
    

    You probably won't do that in production.

提交回复
热议问题