Strange: compiles as Annotation but not as a method

O

Olli Plough

Hello,

I have an annotation like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)

public @interface ContextualPath
{
public Class<? extends MyInterface>[] nodes();
}

Now I define this annotation for a class:

@ContextualPath(nodes = { MyObject.class })
public class Foo
{
}

where MyObject implements MyInterface.

This compiles fine without problem. However it does not compile if
expressed within a method. Compiler errors for method
Bar.getContextualPath1:

* Type mismatch: cannot convert from Class<MyObject> to
Class<MyInterface>
* Cannot create a generic array of Class<MyInterface>

On the contrary, Bar.getContextualPath2 compiles fine.

class Bar
{

public Class<? extends IModel>[] getContextualPath1()
{
new Class<IModel>[]
{ MyObject.class };
}

public Class<? extends IModel>[] getContextualPath2()
{
// compiles without problem
return
getClass().getAnnotation(ContextualPathNodes.class).nodes();
}
}

There seems to be something special with annotations that I don't get.
Most of all I don't understand why it is allowed for an annotation but
not within a class. Would be gratefull if some knowledgeable person
out there could shed some light on this for me.

Thanks, Oliver
 
D

Daniel Pitts

Olli said:
Hello,

I have an annotation like this:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)

public @interface ContextualPath
{
public Class<? extends MyInterface>[] nodes();
}

You're mixing generics with arrays... Can't do that unfortunately. I
don't really see a way around that in this case either.
 
O

Olli Plough

You're mixing generics with arrays... Can't do that unfortunately. I
don't really see a way around that in this case either.

Hi Daniel,

thanks for that one. Really didn't know this.

Cheers, Olli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top