java的注解是java5.0版本引入的,我们在使用框架时也经常见到它的身影。JDK自身提供的一个非常常见的注解就是@Override,他能告诉编译器这是一个重载方法,若父类不存在该方法,编译器就会报错。但你重载一个方法却不用这个注解,也是完全不影响运行结果的。
那什么是java注解呢?Java提供的一种源程序中的元素关联任何信息和任何元素的途径和方法。下面我讲几种关于注解的分类:
说完分类,我们再来说说元注解。元注解简单来说就是注解的注解。
它这个继承用在接口上是不起效果的,只有用在类上才行,而且继承只会继承类上的注解
而不会继承(已被重写的)方法上的注解。
下面来一个注解解析的简单小栗子:
package Anno;
import java.lang.annotation.Documented;
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({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Description {
//无参无异常
String desc();
String author();
int age() default 18;
}
package Anno;
import test.Person;
@Description(author = "czj", desc = "class")
public class Haveanno implements Person {
@Override
@Description(author = "czj", desc = "method")
public String name() {
// TODO Auto-generated method stub
return null;
}
@Override
public int age() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void sing() {
// TODO Auto-generated method stub
}
}
package Anno;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
public class ParseAnn {
public static void main(String[] args) {
// TODO Auto-generated method stub
//使用类加载器加载类
try {
Class c = Class.forName("Anno.Haveanno");
//找到类上面的注解
boolean isExist = c.isAnnotationPresent(Description.class);
//如果该注解存在
if(isExist) {
Description description = (Description) c.getAnnotation(Description.class);
//输出desc的值
System.out.println(description.desc());
}
//找到方法上的注解
Method[] methods = c.getMethods();
for(Method method : methods) {
boolean isMeExist = method.isAnnotationPresent(Description.class);
if(isMeExist) {
Description description = (Description) method.getAnnotation(Description.class);
System.out.println(description.desc());
}
}
//另一种找到方法上的注解写法
for(Method method : methods) {
Annotation[] annotations = method.getAnnotations();
for(Annotation annotation : annotations) {
if(annotation instanceof Description) {
Description description = (Description) annotation;
System.out.println(description.desc());
}
}
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注解在框架中使用的非常多,如Hibernate,spring等等,但为什么要使用注解呢?