2011-08-23 10 views
10

इस कोड पर विचार करें:एनोटेशन सदस्यों के रूप में इंटरफेस की अनुमति क्यों नहीं है?

@Retention(RetentionPolicy.RUNTIME) 
@Target(ElementType.METHOD) 
public @interface Bar { 
    Foo foo() default FooImpl.FooConstant; 
} 

कंपाइलर त्रुटि:

annotation value not of an allowable type

यदि मैं Foo के साथ Foo को प्रतिस्थापित करता हूं तो कोड स्वीकार किया जाता है।

इस व्यवहार का कारण क्या है?

उत्तर

7

If I replace Foo with FooImpl the code is accepted.

यदि यह FooImpl एक enum है, तो मैं बहुत ही आश्चर्यचकित हूं।

एनोटेशन सदस्यों केवल निम्न हो सकते हैं:

  • आदिम प्रकार
  • स्ट्रिंग
  • कक्षा शाब्दिक
  • एनोटेशन
  • enum आइटम
  • या 1-आयामी में से किसी की सरणियों

It is a compile-time error if the return type of a method declared in an annotation type is any type other than one of the following: one of the primitive types, String, Class and any invocation of Class, an enum type (§8.9), an annotation type, or an array (§10) of one of the preceding types. It is also a compile-time error if any method declared in an annotation type has a signature that is override-equivalent to that of any public or protected method declared in class Object or in the interface annotation.Annotation.

स्रोत: JLS

3

http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.7

एनोटेशन सदस्य प्रकारों में से एक होना चाहिए: आदिम, स्ट्रिंग, क्लास, एक Enum, ऊपर

में से किसी की एक सरणी यह ​​एक संकलन समय त्रुटि है अगर तत्व प्रकार है ElementValue के अनुरूप नहीं है।

आशा है कि इससे मदद मिलती है!

रूप में अच्छी तरह इस दस्तावेज़ में एक ही मिला:

http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

"वापसी प्रकार के पुरातन, स्ट्रिंग, क्लास, enums, एनोटेशन, और पूर्ववर्ती प्रकार के सरणियों प्रतिबंधित कर रहे हैं।" जैसा कि बताया गया है "इंटरफ़ेस" की अनुमति नहीं है।

+0

मैं पहले वाक्य को पूरा, दूसरा एक समस्या लगती है। मुझे आश्चर्य है कि एनोटेशन में इसकी अनुमति क्यों नहीं है ... – soc

+3

@soc * मैं पहली वाक्य को पूरा करता हूं * नहीं, आप नहीं करते हैं। 'कक्षा fooType() 'मान्य होगा, 'Foo foo()' नहीं है। –

+0

एक विधि के रूप में फू फू() पर विचार करें (केवल सादगी के लिए) ... क्या हम एक विधि के लिए रिटर्न प्रकार के रूप में इंटरफ़ेस का उल्लेख कर सकते हैं ??? :) – Nik