自定义注解Annotation的注释
1.很不错的一个例子
Name姓名注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Name {
String value() default "";
}
Gander性别注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Gender {
public enum GenderType {
Male("男"),
Female("女"),
Other("中性");
private String genderStr;
private GenderType(String arg0) {
this.genderStr = arg0;
}
@Override
public String toString() {
return genderStr;
}
}
GenderType gender() default GenderType.Male;
}
Profile个人资料注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Profile {
public int id() default -1;
public int height() default 0;
public String nativePlace() default "";
}
一个简单的处理器
public class CustomUtils {
public static void getInfo(Class<?> clazz) {
String name = "";
String gender = "";
String profile = "";
Field fields[] = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(Name.class)) {
Name arg0 = field.getAnnotation(Name.class);
name = name + arg0.value();
Log.i("Gmw", "name=" + name);
}
if (field.isAnnotationPresent(Gender.class)) {
Gender arg0 = field.getAnnotation(Gender.class);
gender = gender + arg0.gender().toString();
Log.i("Gmw", "gender=" + gender);
}
if (field.isAnnotationPresent(Profile.class)) {
Profile arg0 = field.getAnnotation(Profile.class);
profile = "[id=" + arg0.id() + ",height=" + arg0.height() + ",nativePlace=" + arg0.nativePlace() + "]";
Log.i("Gmw", "profile=" + profile);
}
}
}
}
使用自定义注解:
public class Person {
@Name("阿特罗伯斯")
private String name;
@Gender(gender = Gender.GenderType.Male)
private String gender;
@Profile(id = 1001, height = 180, nativePlace = "CN")
private String profile;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getProfile() {
return profile;
}
public void setProfile(String profile) {
this.profile = profile;
}
}
运行:
CustomUtils.getInfo(Person.class);
结果
I/Gmw: gender=男
I/Gmw: name=阿特罗伯斯
I/Gmw: profile=[id=1001,height=180,nativePlace=CN]
2.若有所思….
3.最后
造神计划。