Java中的注解的作用:
Java代码的特殊标记,他为在Java程序中无法表达的额外信息提供了一种表达方式!
下面来看自定义注解和反射获取·注解
package review.annotationOrThread;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest2 {
String typeConn() default "SQL";
}
为类添加注解
package review.annotationOrThread;
@AnnotationTest2(typeConn="SQL")
public class AnnotationPeople {
privateString name;
private intage;
publicAnnotationPeople() {
}
publicAnnotationPeople(String name, int age) {
this.name =name;
this.age =age;
}
@AnnotationTest2(typeConn="SQL")
publicString getName() {
returnname;
}
public voidsetName(String name) {
this.name =name;
}
public intgetAge() {
returnage;
}
public voidsetAge(int age) {
this.age =age;
}
}
输出注解信息:
package review.annotationOrThread;
import java.lang.annotation.Annotation;
public class AnnotationTest {
publicstatic void main(String[] args) {
AnnotationPeople annotationPeople =new AnnotationPeople();
Annotation[]annotations =annotationPeople.getClass().getAnnotations();
for(Annotation annotation:annotations){
System.out.println(annotation);
}
}
}
下面来看自定义注解和反射获取·注解
package review.annotationOrThread;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AnnotationTest2 {
String typeConn() default "SQL";
}
为类添加注解
package review.annotationOrThread;
@AnnotationTest2(typeConn="SQL")
public class AnnotationPeople {
privateString name;
private intage;
publicAnnotationPeople() {
}
publicAnnotationPeople(String name, int age) {
this.name =name;
this.age =age;
}
@AnnotationTest2(typeConn="SQL")
publicString getName() {
returnname;
}
public voidsetName(String name) {
this.name =name;
}
public intgetAge() {
returnage;
}
public voidsetAge(int age) {
this.age =age;
}
}
输出注解信息:
package review.annotationOrThread;
import java.lang.annotation.Annotation;
public class AnnotationTest {
publicstatic void main(String[] args) {
AnnotationPeople annotationPeople =new AnnotationPeople();
Annotation[]annotations =annotationPeople.getClass().getAnnotations();
for(Annotation annotation:annotations){
System.out.println(annotation);
}
}
}