What is the difference between java.lang.Void and void?

前端 未结 6 556
心在旅途
心在旅途 2020-11-29 03:27

In API

\"The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.\"

6条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 03:58

    Void is useful because sometimes you need to specify the return type of a method outside the method itself.

    For example take this java 8 lambda expression, which checks whether an EventResource object has certain properties, using a method called checkBenefitConcertInCentralPark, passed into the method checkCreatedEvent:

    eventChecker.checkCreatedEvent(TestEvents::checkBenefitConcertInCentralPark);
    

    The checkBenefitConcertInCentralPark method is defined like this (note the use of Void):

        public static Void checkBenefitConcertInCentralPark(EventResource eventResource) { 
            // JUnit code here...
            // assertThat(blablabla  :)  )
    
            return null; // we can only return null at the end of a method when returning Void
        }
    

    and then the checkBenefitConcertInCentralPark method is passed into the method checkCreatedEvent.

        // Function describes the checkBenefitConcertInCentralPark method
        public void checkCreatedEvent(Function function) { 
            function.apply(this.eventResource);
        }
    

提交回复
热议问题