黑马程序员技术交流社区
标题:
关于注解调用问题
[打印本页]
作者:
包志恒
时间:
2011-7-26 17:23
标题:
关于注解调用问题
package Annotion;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE ,ElementType.METHOD})
public @interface MyAnnotion {
String value();
String color() default "red";
}
package Annotion;
@MyAnnotion(value = "acc")
public class AnnotionTest {
/**
* @param args
*/
@MyAnnotion(value="str",color="green")
public static void main(String[] args) {
// TODO Auto-generated method stub
if(AnnotionTest.class.isAnnotationPresent(MyAnnotion.class))
{
MyAnnotion annotation = (MyAnnotion) AnnotionTest.class.getAnnotation(MyAnnotion.class);
System.out.println(annotation.value());
System.out.println(annotation.color());
}
printString("看灰机");
}
@Deprecated
public static void printString(String str)
{
System.out.println(str);
}
}
请问我在方法上的@MyAnnotion(value="str",color="green")
为什么打印出来的还是
acc
red
为什么不是
str
green 呢
作者:
匿名
时间:
2011-7-26 18:28
使用您的语句,获得的是类上的Annotation。
若想获得某个方法的Annotation,则需要先获取那个方法的Method对象,然后再调用这个Method对象的Annotation。
范例1:如您所愿。[code=java]@MyAnnotion(value = "acc")
public class AnnotationTest {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
*/
@MyAnnotion(value="str",color="green")
public static void main(String[] args) throws SecurityException, NoSuchMethodException {
// TODO Auto-generated method stub
if(AnnotationTest.class.isAnnotationPresent(MyAnnotion.class))
{
MyAnnotion annotation = (MyAnnotion) AnnotationTest.class.getMethod("main",String[].class).getAnnotation(MyAnnotion.class);
System.out.println(annotation.value());
System.out.println(annotation.color());
}
printString("看灰机");
}
@Deprecated
public static void printString(String str)
{
System.out.println(str);
}
} [/code]本范例的核心代码:
“AnnotationTest.class.getMethod("main",String[].class).getAnnotation(MyAnnotion.class); ”
程序输出结果:[code=java]str
green
看灰机[/code]
作者:
匿名
时间:
2011-7-26 18:42
哈哈 原来如此 灰常感谢 对了你怎么头像和那个周杰伦的一样啊 你是他的偶像么:lol
作者:
匿名
时间:
2011-7-26 19:08
那个周杰伦暂时消失了。
如果您找他有事,去咱们的 情感发泄区,也许会有一些蛛丝马迹。
作者:
巴特ê
时间:
2012-5-4 22:32
顶一个啊!!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2