首页 > 编程知识 正文

java数据库连接步骤,java反射获取注解的值

时间:2023-05-03 15:29:38 阅读:134507 作者:2887

注释和反射

注释是通过反射获取的。 首先,若要确定是否已对Class对象应用了注释,请使用Class对象的isAnnotationPresent ()方法

publicbooleanisannotationpresent (classextendsannotationannotationclass ) }

然后使用getAnnotation ()方法获取Annotation对象。

publicagetannotation (classannotationclass ) }

或者是getAnnotations ()方法。

公共分析[ ] get annotations { }

前者方法返回指定类型的注释,而后者方法返回此元素的所有注释。

如果获取的Annotation不为空,则可以调用属性方法。 例如

@TestAnnotation ()

公共类测试{

publicstaticvoidmain (字符串[ ] args ) {

booleanhasannotation=test.class.isannotationpresent (test annotation.class );

硬件注释(if ) {

testannotationtestannotation=test.class.get annotation (test annotation.class;

system.out.println(id: ) testannotation.id;

system.out.println(msg: ) testannotation.msg;

}

}

}

程序的执行结果如下

id:-1

msg:

这是TestAnnotation中id和msg的默认值。

在上面的例子中,只要检查了类上的注释,属性、方法上的注释也同样可以。 还是要着手反射。

@testannotation(msg='Hello ' ) ) ) ) ) ) ) ) ) ) ) )。

公共类测试{

@check(value='hi ' ) )。

int a;

@Perform

公共语音测试方法

@suppresswarnings('deprecation ' ) ) ) )。

公共语音测试1 () {

Hero hero=new Hero (;

hero.say (;

hero.speak (;

}

publicstaticvoidmain (字符串[ ] args ) {

booleanhasannotation=test.class.isannotationpresent (test annotation.class );

硬件注释(if ) {

testannotationtestannotation=test.class.get annotation (test annotation.class;

//获取类的注释

system.out.println(id: ) testannotation.id;

system.out.println(msg: ) testannotation.msg;

}

try {

fielda=test.class.getdeclaredfield (' a );

a .设置访问(true );

//获取成员变量的注释

check check=a.get annotation (check.class );

if (检查!=null ) {

system.out.println (' check value : ' check.value ) );

}

methodtestmethod=test.class.getdeclaredmethod (' test method );

测试方法!=null ) {

获取//方法中的注释

annotation [ ] ans=test method.get annotations (;

for(intI=0; i ans.length; I ) {

system.out.println (' methodtestmethodannotation : ' ans [ I ].annotation type ().getSimpleName );

}

}

}catch(nosuchfieldexceptione ) )

//todo自动生成的catch block

e .打印堆栈跟踪(;

system.out.print ln (e.getmessage );

}catch(securityexceptione ) {

//todo自动生成的catch block

e .打印堆栈跟踪(;

system.out.print ln (e.getmessage );

}catch(nosuchmethodexceptione ) )

//todo自动生成的catch block

e .打印堆栈跟踪(;

system.out.print ln (e.getmessage );

}

}

}

结果如下

id:-1

MSG:你好

check value:hi

元数据元数据:性能

请注意,要在运行时正确提取注释,必须@ retention (retention policy.runtime )。

------------------------- -本文来自frank909的CSDN博客,全文地址为: 33330

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。