简体   繁体   中英

Java: how to make a method return an array of classes

I want a method to return some thing like:

{classA.class,classB.class,classC.class}

I've tried:

public Class<?>[] methodeName()
{
   return {classA.class,classB.class,classC.class};
}

but this won't complie, as Java thinks that I want to create a class ... I don't want to use any lists ....

Any suggestions?

You need to properly create the array:

return new Class<?>[]{classA.class, classB.class, classC.class};

What you're trying to do only works in with array declarations:

Class<?>[] classes = {classA.class, classB.class, classC.class};  // <--
return classes;

Array creation expressions are detailed in JLS §15.10 .

You have to tell that the type is Class

return new Class[] {classA.class, classB.class, classC.class};

Where

 return {classA.class,classB.class,classC.class};// Compiler is asking  what 
                 type of array it is ?? I can't store without knowing its type.

Try this one

    public Class<?>[] methodeName()
    {
       Class<?>[] classes= {classA.class,classB.class,classC.class};
       return classes;
    }

This'll work

Class[] fun(){
    Class[] i = {classA.class,classB.class,classC.class};
    return i;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM