import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class DemoMain {
public static void main(String[] args) {
//定义两个被标注了@CalculateAnnotation的对象
DemoEntity entity1 = new DemoEntity(123, "332");
DemoEntity entity2 = new DemoEntity(22, "32");
DemoEntity result = new DemoEntity();//结果对象
//获取该类的所有field
Field[] fields = DemoEntity.class.getDeclaredFields();
//遍历所有field,同时获取每个field上的注解对象,存放到map中
Map annotationMap = new HashMap();
for (Field field : fields) {
CalculateAnnotation annotation = field.getAnnotation(CalculateAnnotation.class);
annotationMap.put(field, annotation);
}
//遍历map,依据field上的annotation处理每个filed
for (Map.Entry entry : annotationMap.entrySet()) {
Field field = entry.getKey();
CalculateAnnotation annotation = (CalculateAnnotation) entry.getValue();
//通过注解获取到对象的值,并且处理运算出结果对象的值
Object entity1Value = null;
Object entity2Value = null;
Object resultVelue = null;
try {
// 该处注意,对于private属性是不可以直接访问的,需要先设置accessible。
// 另一只方式是通过属性的getter和setter获取和设置值
if (!field.isAccessible()) {
field.setAccessible(true);
}
if (annotation.needStr2Num()) {
entity1Value = Integer.parseInt(field.get(entity1).toString());
entity2Value = Integer.parseInt(field.get(entity2).toString());
} else {
entity1Value = field.get(entity1);
entity2Value = field.get(entity2);
}
if (annotation.type().getValue() == CalculateAnnotation.Type.ADD.getValue()) {
resultVelue = (Integer) entity1Value + (Integer) entity2Value;
} else if (annotation.type().getValue() == CalculateAnnotation.Type.SUBTRACT.getValue()) {
resultVelue = (Integer) entity1Value - (Integer) entity2Value;
}
if (annotation.needStr2Num()) {
resultVelue = resultVelue.toString();
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
//通过set方法将结果值设置到结果对象中
try {
String setMethodName = "set" + field.getName().substring(0, 1).toUpperCase() + field.getName().substring(1);
Method method = DemoEntity.class.getMethod(setMethodName, field.getType());
//此处在之前已将将resultValue又转换为String类型,所以不需要再转换
// if (field.getType() == String.class) {//类型判断可以直接通过==判断
// method.invoke(result, resultVelue.toString());
// } else {
method.invoke(result, resultVelue);//resultValue不管是Integer还是int都可以执行
// }
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
System.out.println(result);
}
}