Java自定义注解 (二)

2014-11-24 07:34:33 · 作者: · 浏览: 2
n.value();
filed.setAccessible(true);
setterName.invoke(use, value);
}
}
}

use.say();
}
}
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class DefaultTest {
public static void main(String args[]) throws Exception{
DefaultUse use = new DefaultUse();

//Default注解的处理过程
//这里使用反射机制完成默认值的设置
Field[] fileds = use.getClass().getDeclaredFields();


for(Field filed : fileds){
Default annotation = filed.getAnnotation(Default.class);
if(annotation != null){
PropertyDescriptor pd = new PropertyDescriptor(filed.getName(), DefaultUse.class);
Method setterName = pd.getWriteMethod();

if(setterName!=null){
String value = annotation.value();
filed.setAccessible(true);
setterName.invoke(use, value);
}
}
}

use.say();
}
}

摘自 God's blog