In the first code example of this beginners guide to Dependency Injection I encountered some new constructs of which I am not sure that I totally understand:
// Instantiate CabAgency, and satisfy its dependency on an airlineagency.
Constructor constructor = cabAgencyClass.getConstructor
(new Class[]{AirlineAgency.class});
cabAgency = (CabAgency) constructor.newInstance
(new Object[]{airlineAgency});
What does new Class[]{AirlineAgency.class} actually mean and do?
I understand that its goal is to create a Constructor instance for AirlineAgency.class but how does the syntax new Class[]{} achieve this?
Why the array notion [] when there is only one object involved?
What is the {} syntax here? Why not ()?
new Class[] { AirlineAgency.Class }creates an one-element array ofClassobjects and initializes the only element to beAirlineAgency.class. It is similar tonew int[] { 42 }.The code is essentially equivalent to this:
The
Class.getConstructormethod wants an array of parameter types for the constructor (to find the right overload to use), and similarlyConstructor.newInstancewants an array of arguments. That’s why it’s done that way.