2

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?

3
  • 2
    Let's take a look at the bigger picture: why do you want to return an array of classes and why don't you want to use a List? Commented Oct 25, 2013 at 14:15
  • there is even more code to write to create them. Commented Oct 25, 2013 at 15:03
  • Not really: Arrays.asList(classA.class, classB.class, classC.class); The big question is, why do you need a method to return a collection of classes? Commented Oct 25, 2013 at 16:25

4 Answers 4

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I'v tried to do it in a too complicated way ... what I really needed was simply a static arry in my class and no methode returning one as I just wanted a static array of classes :-)
0

Try this one

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

Comments

0

This'll work

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.