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

没有spring如何使用注解下篇

2014-01-05 11:21 357 查看
Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。
注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。包含在 java.lang.annotation 包中。
首先自定义一个注解 关键字是:@interface
@Retention(RetentionPolicy.RUNTIME)//编译器将把注释记录在类文件中,在运行时 VM 将保留注释,因此可以反射性地读取。
//ps:只有当类注解使用了RetentionPolicy.RUNTIME保留策略,才能在运行时,通过java反射机制获取
@Target({ElementType.METHOD})//目标使用注解的是方法

public @interface ActionAnnotation {
boolean UseService() default true; //在后面遍历的时候就可以取出这些值作为条件,好似解决了struts2里面Action方法公开的缺陷(怀疑)?
boolean Initialize() default true;//同上,ps 可以初始化一些参数例如生成action实例
}
//取出注解的方法 参照网上例子:

////////////////////////////////////////////////////////////////////////

import java.lang.annotation.Documented;

import java.lang.annotation.Inherited;

import java.lang.annotation.Retention;

import java.lang.annotation.Target;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.ElementType;

@Documented @Inherited @Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.TYPE)

public @interface AkClass {

String value() default "hello";

}

/////////////////////////////////////////////////////////////////
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface AkMethod {
boolean ischeck() default true;
}

//////////////////////////////////////////////////////////////////////
@AkClass()
public interface AkClassTest {
@AkMethod()
public abstract void getAK();
}

//////////////////////////////////////////////////////////////////////
public class MyAnnotation{
public static void main(String[] args) {
//判断某个类是否是注解
System.out.println("判断对象是否为注解类型:"+AkClassTest.class.isAnnotation());
System.out.println("调用指定的类注解属性值:"+AkClassTest.class.getAnnotation(AkClass.class).value());

//获取某个具体类的所有注解
Annotation[] annotations = AkClassTest.class.getAnnotations();
for(Annotation annotation : annotations){
// 判断当前注解对象是否为自定义注解
if(annotation.annotationType() == AkClass.class){
System.out.println("类注解名称:"+AkClass.class.getSimpleName());
Method[] methods = AkClass.class.getDeclaredMethods();
for(Method method : methods){
System.out.println("类注解方法:"+method.getName());
}
System.out.println();
}
}

System.out.println("获取某个类中所有方法的所有方法注解");
Method[] methods = AkClassTest.class.getMethods();
for(Method method : methods){
System.out.println("类方法名字:"+method.getName());
System.out.println("调用方法注解的属性值:"+method.getAnnotation(AkMethod.class).ischeck());
Annotation[] mAnnotations = method.getAnnotations();
for(Annotation mAnnotation : mAnnotations){
if(mAnnotation.annotationType() == AkMethod.class){
System.out.println("注解名:"+AkMethod.class.getSimpleName());
}
}
}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐