这篇文章我们来谈谈java的注解,java的注解分为三种一种是source,也就是在源文件的时候有效,还有一种是class,是在class中有效,当然我们写的都是最后一种也就是runtime,也就是运行时有效的,这里我只是写了一个简单的例子来作为注解的小的自定义注解demo,这里并没有仔细去研究这个,因为毕竟我们在很多时候是不需要写注解的,但是知道对我们并没有什么坏处。
对了这里顺便说说java里面的三个注解:
override,对方法的重写的检查
deprecated,对不再使用的方法进行注解
suppressWarnings 基本上就是消除一些警告的
大概就这样,看看一个简单的自定义annotation的代码吧
代码:
package www.jk.annotation;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
//define the action scope of the myFactor
@Retention(value = RetentionPolicy.RUNTIME)
// define the Annotation
@interface myFactor {
public String name() default "ni hao ";
public String val();
}
public class Test {
public static void main(String[] args) {
// get the Class object of the Stu
Class<?> cla = Stu.class;
// get the Annotations of the Stu
Annotation an[] = cla.getAnnotations();
for (int i = 0; i < an.length; i++) {
// print each annotation
System.out.println(an[i]);
}
}
}
@myFactor(val = "what")
class Stu {
String name = "wang";
}