1

Currently I have the following code to test my class...

@RunWith(Suite.class)
@SuiteClasses( { MyClass.class, MyNewClass } )
public class AllTests {
    public static void suite() {        
    }
}

What I'd like to do would be the following, but it's syntactically incorrect - what would be the correct format?...

 Class<?>[] classArray = new Class<?>[] {
        MyClass.class, MyNewClass.class
  };

 @RunWith(Suite.class)
    @SuiteClasses( classArray  )
    public class AllTests {
        public static void suite() {        
        }
    }
1
  • try removing the Generic <?> Commented Nov 14, 2012 at 14:51

3 Answers 3

4

Unfortunately you can't. Annotations need to take compile-time constants, so you have to use { MyClass.class, MyNewClass.class }.

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

1 Comment

This is the correct answer. It's about what you feed to an annotation, not how you've declared the array variable.
1

--- Update ---

The problem seems to stem from Annotations. Annotations require compile time constants, which means you cannot "build an array" of classes in a manner that might have you reassigning the array, or modifying it before the annotated method could access it.

Credit to artbristol for pointing out the obvious. Initially I started down the wrong path, which was to attempt to find out why your array did compile in my 1.7 environment.

Actually, the compile time constant restriction on Annotations makes perfect sense when considering that Annotations are meant to extends java programming via declarative means.

--- Original Post ---

Instead of attempting a wildcard, use

 Class<Object>[] classArray = new Class<Object>[] { .... };

It semi-defeats the purpose of generics, since everything extends from Object; but, it will satisfy the "shove anything into it" requirements you need.

Comments

1

By K.Sierra from "SCJP study guide": "Keep in mind that the wildcards can be used only for reference declarations (including arguments, variables, return types, and so on). They can't be used as the type parameter when you create a new typed collection. Think about that—while a reference can be abstract and polymorphic, the actual object created must be of a specific type."

List<?> foo = new ArrayList<? extends Animal>();

Problem: you cannot use wildcard notation in the object creation. So the new ArrayList() will not compile.

EDIT: @artbristol pointed another problem which is compile-time constant passed to the annotation. Look at the responses in this thread, they might be helpful. One of them suggests ENUM as a workaround. How to use an array constant in an annotation

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.