android&java註解詳解
阿新 • • 發佈:2019-02-16
package com.example.zwr.annotationdemo;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* author : zhongwr on 2016/12/1
* 獲取杯子的註解
*/
public class CupAnnotationUtil {
public static String getAnnotationInfo(Class<?> targetClass) {
StringBuilder annotationInfo = new StringBuilder();
//判斷targetClass類宣告是否用了註解:如在類宣告前用了註解則可通過這個獲取類註解的value 舉例:@CupAnnotation public class Cupdemo{}
CupAnnotation cupAnnotation = targetClass.getAnnotation(CupAnnotation.class);
annotationInfo.append("類宣告用的註解:");
annotationInfo.append("\n");
annotationInfo.append("類 :" + targetClass.getName());
if (null == cupAnnotation) {
annotationInfo.append("類宣告沒用到註解 :");
annotationInfo.append("\n");
} else {
annotationInfo.append("杯子標籤:" + cupAnnotation.id() + " 杯子顏色:" + cupAnnotation.color() + " 杯子形狀:" + cupAnnotation.shaper());
}
annotationInfo.append("\n");
annotationInfo.append("方法宣告用的註解:");
annotationInfo.append("\n");
//判斷targetClass所有方法是否有用到註解
Method methods[] = targetClass.getDeclaredMethods();
if (null != methods) {
int length = methods.length;
for (int i = 0; i < length; i++) {
CupAnnotation cupMethodAnno = methods[i].getAnnotation(CupAnnotation.class);
if (null != cupMethodAnno) {//方法中使用了註解則不會為空
annotationInfo.append("註解方法名:" + cupMethodAnno.methodName());
} else {
annotationInfo.append("沒使用註解的方法名:" + methods[i].getName());
}
annotationInfo.append("\n");
}
}
annotationInfo.append("\n");
annotationInfo.append("屬性宣告用的註解:");
annotationInfo.append("\n");
//判斷targetClass所有屬性是否有用到註解
Field[] fields = targetClass.getDeclaredFields();
if (null != fields) {
int length = fields.length;
for (int i = 0; i < length; i++) {
CupAnnotation cupFieldAnno = fields[i].getAnnotation(CupAnnotation.class);
if (null != cupFieldAnno) {//方法中使用了註解則不會為空
annotationInfo.append("屬性註解資訊:");
annotationInfo.append("\n");
annotationInfo.append("屬性名:" + fields[i].getName() + " 杯子標籤:" + cupFieldAnno.id() + " 杯子顏色:" + cupFieldAnno.color() + " 杯子形狀:" + cupFieldAnno.shaper());
} else {
annotationInfo.append("沒使用註解的屬性名:" + fields[i].getName());
}
annotationInfo.append("\n");
}
}
return annotationInfo.toString();
}
}