succeed
succeed

Reputation: 1039

Understanding Java new Class[] array and implementation

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?

Upvotes: 0

Views: 140

Answers (5)

user2575725
user2575725

Reputation:

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};

Upvotes: 1

President James K. Polk
President James K. Polk

Reputation: 42009

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.

Upvotes: 2

ajb
ajb

Reputation: 31699

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.

Upvotes: 0

Pramod
Pramod

Reputation: 806

It is array of wildcard type. See this for more

Upvotes: 0

Maaaatt
Maaaatt

Reputation: 449

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

Upvotes: 0

Related Questions