Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the syntax `new Class[]{}` work?

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 ()?

like image 487
Regex Rookie Avatar asked Jul 02 '11 21:07

Regex Rookie


People also ask

How do you use class syntax?

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.

What does class New do in Java?

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.


1 Answers

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.

like image 153
hammar Avatar answered Sep 20 '22 12:09

hammar