以下学习注解时的代码,直接粘贴就可以运行。
注解几点
1.自定义的注解在默认情况下自动继承了Annotation接口。
2.Annotation是个接口,不是注解。
3.自定义的注解是注解,而不是接口。
4.自定义的注解是不能够其他注解所继承的。
5.注解可以修饰注解。
6.使用注解可以提取类的信息。
7.很多框架都是以注解来实现的。
8.注解是从jdk1.5版本开始后的新特性。
9.使用反射技术来获取注解信息的时候,要注意是否是同一个类加载器,或者会导致类加载不上的bug。
以下是实现一个注解并且运行的代码
1.自定义一个枚举
package com.annotation;
public enum AnnotationEnum {
ADD, SUB, MUI
}
2.自定义一个注解
package com.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value = ElementType.METHOD)
// 定义注解的运行时机
@Retention(value = RetentionPolicy.RUNTIME)
// 定义注解会被编译,保留到class文件中,同时可以通过反射方式获取的到
@Inherited //定义该注解可以被子类继承的,但是不能够做反射之类的动作
public @interface MyAnnotation {
String[] hello() default "hello";// 定义默认一个值
String world();
AnnotationEnum aEnum();
}
3.定义一个使用自定义注解的类
package com.annotation;
public class MyAnnotationTest {
@MyAnnotation(hello = { "sayHello", "sayHello1" }, world = "world", aEnum = AnnotationEnum.ADD)
public void sayHello(String name) {
System.out.println(name + " say hello.");
}
public void sayHello() {
}
}
4.测试
package com.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class Client {
public static void main(String[] args) throws Exception {
MyAnnotationTest mt = new MyAnnotationTest();
Class<MyAnnotationTest> mClass = MyAnnotationTest.class;
System.out
.println("--------------Method Reflect Begin-----------------------");
Method method = mClass.getDeclaredMethod("sayHello",
new Class[] { String.class });
method.invoke(mt, new Object[] { "Jhon" });
System.out
.println("--------------Method Reflect End-----------------------");
System.out
.println("--------------Method Reflect Get Annotation Begin-----------------------");
System.out.println(method.isAnnotationPresent(MyAnnotation.class));
MyAnnotation antotation = method.getAnnotation(MyAnnotation.class);
for (String temp : antotation.hello()) {
System.out.print(temp + " ");
}
System.out.println();
System.out.println(antotation.aEnum());
System.out.println(antotation.world());
for (Annotation temp : method.getDeclaredAnnotations()) {
System.out.println(temp);
}
System.out
.println("--------------Method Reflect Get Annotation End-----------------------");
}
}
5.给自定义的注解使用@Inherited注解,让子类可以继承父类的注解。
package com.annotation;
public class SubMyAnnotationTest extends MyAnnotationTest {
/*
* 如果子类只是继承父类,而不覆写(Override)对应的使用了inherited注解的方法,则子类依然是会继承父类对应方法的注释的;否则如果子类覆写
* (Override)了该方法,则对应的注解同样会被覆盖掉,即此时父类方法的注解将不被子类方法所继承。
*/
@MyAnnotation(hello = { "subSayHello", "subSayHello1" }, world = "subWorld", aEnum = AnnotationEnum.ADD)
@Override
public void sayHello(String name) {
super.sayHello(name);
}
}