您的位置:首页 > 编程语言 > Java开发

Java注解Annotation学习笔记

2017-04-06 23:00 387 查看

一、自定义注解

1. 使用关键字 @interface2. 默认情况下,注解可以修饰 类、方法、接口等。3. 如下为一个基本的注解例子:
//注解中的成员变量非常像定义接口

public @interface MyAnnotation {

//不带有默认值

String name();


//带有默认值

int age() default 20;

}

[/code]4. Reflect中3个常见方法解读getAnnotion(Class<T> annotationClass) 返回该元素上存在的,指定类型的注解,如果没有返回null

Annotation[] getAnnotations() 返回该元素上所有的注解。

boolean isAnnotationPersent(Class<? extends Annotation> annotationClass) 判断该院上上是否含有制定类型的注释。

二、元注解

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

public @interface ValueBind {


filedType type();


String value() default "SUSU";


enum filedType {

STRING, INT

}

}

[/code]其中@Target 和 @Retention为元注解。@Retention有如下几种取值:



其中通常都是RetentionPolicy.RUNTIME

@Target有如下几个取值:


@Inherited 表示该注解具有继承性。

三、Demo

1. ValueBind注解
@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@Documented

public @interface ValueBind {


filedType type();


String value() default "SUSU";


enum filedType {

STRING, INT

}

}

[/code]

2. Person类
public class Person implements Serializable {


private String name;


private int age;


public String getName() {

return name;

}


@ValueBind(type = ValueBind.filedType.STRING, value = "LCF")

public void setName(String name) {

this.name = name;

}


public int getAge() {

return age;

}


@ValueBind(type = ValueBind.filedType.INT, value = "21")

public void setAge(int age) {

this.age = age;

}


@Override

public String toString() {

return "Person{" +

"name='" + name + '\'' +

", age=" + age +

'}';

}

}

[/code]
3. Main方法
import java.lang.reflect.Method;


public class Main {


public static void main(String[] args) throws Exception {

Object person = Class.forName("Person").newInstance();

//以下获取的是:类的注解

// Annotation[] annotations = person.getClass().getAnnotations();

Method[] methods = person.getClass().getMethods();

for (Method method : methods) {

//如果该方法上面具有ValueBind这个注解

if (method.isAnnotationPresent(ValueBind.class)) {

//通过这个注解可以获取到注解中定义的

ValueBind annotation = method.getAnnotation(ValueBind.class);

if (annotation.type().equals(ValueBind.filedType.STRING)) {

method.invoke(person, annotation.value());

} else {

method.invoke(person, Integer.parseInt(annotation.value()));

}

}

}

System.out.println(person);

}

}

[/code]输出结果:Person{name='LCF', age=21}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: