##学习笔记–Java注解开发入门
####1.常用三个注解####
@SuppressWarnings() – 去除编译检查提示,如私有的方法和属性没有被使用。
@Override – 标明子类中某个方法是重写了父类方法
@Deprecated – 标明某个方法、类或属性等是过期方法,不推荐使用。
####2.Java元注解####
元注解:描述注解的注解
@Documented – 生成文档时将标注此注释的注解生成文档
@Retention(RetentionPolicy.RUNTIME) – 注解的保留时间,有三种:SOURCE(资源文件保留),CLASS(资源文件和class文件保留),RUNTIME(资源文件、class文件和运行时都保留)。
@Target(ElementType.ANNOTATION_TYPE) – 注解可以作用在那些类型上,如:类、构造方法、普通方法、属性等。
@Inherited:说明子类可以继承父类中的该注解。
####3.开发自己的注解####
开发一个HelloAnnotation注解:
@Documented
@Retention(value = RetentionPolicy.RUNTIME)
@Target(value = {ElementType.TYPE,ElementType.CONSTRUCTOR,ElementType.METHOD,ElementType.FIELD})
public @interface HelloAnnotation
{
String name() default "hello";
}
利用反射使用注解:
1.注解在类上
@HelloAnnotation(name = "xiaoming")
public class MyAnnotation
{
// @HelloAnnotation(name = "xiaoming")
private void say()
{
System.out.println("hello");
}
public void testAnnotion()
{
Class<? extends MyAnnotation> myClass = this.getClass();
if(myClass.isAnnotationPresent(HelloAnnotation.class))
{
HelloAnnotation annotation = myClass.getAnnotation(HelloAnnotation.class);
String name = annotation.name();
System.out.println(name);
}
}
public static void main(String[] args)
{
System.out.println("hello");
MyAnnotation ma = new MyAnnotation();
ma.testAnnotion();
}
2.注解在方法上
//@HelloAnnotation(name = "xiaoming")
public class MyAnnotation
{
@HelloAnnotation(name = "xiaoming")
public void say()
{
System.out.println("hello");
}
public void testAnnotion()
{
Class<? extends MyAnnotation> myClass = this.getClass();
Method method = null;
try
{
method = myClass.getMethod("say",null);
}
catch (NoSuchMethodException e)
{
e.printStackTrace();
}
if(method != null && method.isAnnotationPresent(HelloAnnotation.class))
{
HelloAnnotation annotation = method.getAnnotation(HelloAnnotation.class);
String name = annotation.name();
System.out.println(name);
}
}
public static void main(String[] args)
{
System.out.println("hello");
MyAnnotation ma = new MyAnnotation();
ma.testAnnotion();
}
}
3.注解在类属性上
//@HelloAnnotation(name = "xiaoming")
public class MyAnnotation
{
@HelloAnnotation(name = "xiaoming")
public String aa = "";
// @HelloAnnotation(name = "xiaoming")
public void say()
{
System.out.println("hello");
}
public void testAnnotion()
{
Class<? extends MyAnnotation> myClass = this.getClass();
Field field = null;
try
{
field = myClass.getDeclaredField("aa");
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
if(field != null && field.isAnnotationPresent(HelloAnnotation.class))
{
HelloAnnotation annotation = field.getAnnotation(HelloAnnotation.class);
String name = annotation.name();
System.out.println(name);
}
}
public static void main(String[] args)
{
System.out.println("hello");
MyAnnotation ma = new MyAnnotation();
ma.testAnnotion();
}
}