`
Ydoing
  • 浏览: 100482 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Java注解Annotation简介

 
阅读更多

注解定义和使用

注解定义为:

public @interface AnnotationName{
}

使用注解

@ AnnotationName
public void func(){
}

Java提供了4个元注解

@Retention:保留的阶段。
@Target:注解修饰的目标,可以说类,方法,成员变量,包。
@Documented:是否被javadoc提取成文的。
@Inherited:注解是否能继承。

自定义注解

注解的成员变量定义:

public @interface AnnotationName{
    String name() default "abc";
    int age() default 33;
    boolean flag();
}

其中default修饰的表示默认值。

  • 注意:Annotation修饰类,方法,成员变量后不会自己生效,不会对程序有任何影响。只有为这些注解提供处理的工具类才会有用。

实例

定义注解类

import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Testable {
    boolean isSkiped() default false;
    String name();
}

被注解修饰的类

public class Foo {
    public static void m1() {
        System.out.println("I am m1");
    }
    @Testable(isSkiped = false, name = "methond2")
    public static void m2() {
        System.out.println("I am m2");
    }
    @Testable(name = "methond3")
    public static void m3() {
        System.out.println("I am m3");
    }
    @Testable(isSkiped = true, name = "methond4")
    public static void m4() {
        System.out.println("I am m4");
    }
}

处理注解的工具类

import java.lang.reflect.*;
public class TestAnnotation {
    public static void main(String[] args) throws SecurityException,
            ClassNotFoundException, IllegalAccessException,
            IllegalArgumentException, InvocationTargetException {
        for (Method m : Class.forName("Foo").getMethods()) {
            if (m.isAnnotationPresent(Testable.class)) {
                System.out.print(m.getName()
                        + " is Annotation element, so invoke result is: ");
                m.invoke(null);
            } else {
                System.out.println(m.getName() + " is not Annotation element");
            }
        }
    }
}

输出:

m1 is not Annotation element
m2 is Annotation element, so invoke result is: I am m2
m3 is Annotation element, so invoke result is: I am m3
m4 is Annotation element, so invoke result is: I am m4
wait is not Annotation element
wait is not Annotation element
wait is not Annotation element
equals is not Annotation element
toString is not Annotation element
hashCode is not Annotation element
getClass is not Annotation element
notify is not Annotation element
notifyAll is not Annotation element
<script type="text/javascript"> $(function () { $('pre.prettyprint code').each(function () { var lines = $(this).text().split('\n').length; var $numbering = $('<ul/>').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($('<li/>').text(i)); }; $numbering.fadeIn(1700); }); }); </script>

版权声明:本文为博主原创文章,未经博主允许不得转载。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics