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;
}
}
}
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;
}
}
}