0

Begining Java

Can someone break down whats going on here

protected Class<?>[] getServletConfigClasses() {
    // TODO Auto-generated method stub
    return new Class[] {
            WebApplicationContextConfig.class
    };
}

My understanding is that this is a method which expects its return to be an array of Class object of an unknown type

But what is the return? An instantiation of an anonymous Class object array without a constructor and its implementation block at the same time?

What's the name of this for further reading and I can't seem to find this subject area?

succeed
  • 834
  • 1
  • 11
  • 28
  • https://stackoverflow.com/questions/15177463/initializing-array-with-values-should-i-explicitly-instance-the-class-or-not – ajb Jul 17 '17 at 00:13

5 Answers5

2

There is no anonymous Class object. Class is a java class like any other, but with a name that is bound to confuse Java beginners.

the statement

return new Class[] {
            WebApplicationContextConfig.class
    };

is equivalent to

Class [] result = new Class[1];
result[0] = WebApplicationContextConfig.class;
return result;

WebApplicationContextConfig.class is called a class literal, and here is a some discussion about them.

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
1

It is an array declared with default values. In Java it is short-hand way of making arrays.

String[] names = {"Arvind","Aarav"}; // initialization

Now to re-assign a completely new array.

names = new String[]{"Rajesh","Amit","Mahesh"}; //re-initalization

Same thing with methods, let us say, returning days of week

public String[] weekdays(){
    String[]days={"Sun","Mon","Tue"};
    return days;
}

OR

public String[] weekdays(){
    return new String[]{"Sun","Mon","Tue"};
}

Now about Class[], for type Class possible value is null and SomeClassName.class.

Class stringClass = String.class;
Class[] moreClasses = {Long.class, Boolean.class, java.util.Date.class};
0

It's just declaring an Array of Class and initialize it with one element (The Class definition of WebApplicationContextConfig)

Maaaatt
  • 429
  • 4
  • 14
0

It is array of wildcard type. See this for more

Pramod
  • 806
  • 1
  • 8
  • 10
0

This is an array initializer. When you say

new Something[] { x1, x2, x3 }

it creates a new array of the Something class, and initializes the values to whatever you tell it in the curly braces. The length of the new array is the number of values.

I think you might be confusing it with a very similar syntax:

new Something() { class declarations, method overrides, etc. }

This one creates an anonymous subclass of Something, and it's used a lot for creating anonymous subclasses that implement interfaces. It's not at all related to the array initializer syntax, even though the appearance is pretty close.

ajb
  • 31,309
  • 3
  • 58
  • 84