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 ()
?
The “class” syntaxmethod2() { ... } method3() { ... } ... } Then use new MyClass() to create a new object with all the listed methods. The constructor() method is called automatically by new , so we can initialize the object there.
The Java new keyword is used to create an instance of the class. In other words, it instantiates a class by allocating memory for a new object and returning a reference to that memory. We can also use the new keyword to create the array object.
new Class[] { AirlineAgency.Class }
creates an one-element array of Class
objects and initializes the only element to be AirlineAgency.class
. It is similar to new int[] { 42 }
.
The code is essentially equivalent to this:
Class[] parameterTypes = new Class[1];
parameterTypes[0] = AirlineAgency.class;
Constructor constructor = cabAgencyClass.getConstructor(parameterTypes);
Object[] arguments = new Object[1];
arguments[0] = airlineAgency;
cabAgency = (CabAgency)constructor.newInstance(arguments);
The Class.getConstructor
method wants an array of parameter types for the constructor (to find the right overload to use), and similarly Constructor.newInstance
wants an array of arguments. That's why it's done that way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With