java 反射之自定義註解 – 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;
}
}
}

發佈留言