java 反射之自定义注解

java的自定义注解,使用反射来获取信息并进行相应处理,对于程序员来说很方便。废话少说,直接上代码。

import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;


import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Field;


import org.junit.Test;


public class MyAnotation {


@Test
public void testMyAnotation()
{
MySubObject mySub = new MySubObject();
mySub.setProperty1("property1111");
mySub.setProperty2("property222");

Field[] fields = mySub.getClass().getDeclaredFields();
for(Field field: fields)
{
Annotation ano = field.getAnnotation(Sub.class);
if(ano != null)
{
System.out.println(field.getName());
Sub sub = (Sub)ano;
System.out.println(sub.name());
System.out.println(sub.type());
}
}
}
@Retention(RUNTIME)
@Target({FIELD}) //此注解作用于对象的域上
public @interface Sub {
public String name(); //name属性
public String type(); //type属性
}

public class MySubObject{
@Sub(name="mysubname", type="mysubtype")
private String property1;
private String property2;
public String getProperty1() {
return property1;
}
public void setProperty1(String property1) {
this.property1 = property1;
}
public String getProperty2() {
return property2;
}
public void setProperty2(String property2) {
this.property2 = property2;
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值