目标类:
代码实现:
public class Test{
public static void main(String[] args) {
Properties dingLinkMessageModel = getApiModelProperty("com.tfjybj.msg.model.DingLinkMessageModel");
System.out.println(dingLinkMessageModel);
}
public static Properties getApiModelProperty(String classPath) {
Properties p = new Properties();
try {
// 1.根据类路径获取类
Class<?> c = Class.forName(classPath);
// 2.获取类的属性
Field[] declaredFields = c.getDeclaredFields();
// 3.遍历属性,获取属性上ApiModelProperty的值,属性的名,存入Properties
if (declaredFields.length != 0) {
for (Field field : declaredFields) {
if (field.getAnnotation(ApiModelProperty.class) != null) {
// key和value可根据需求存
// 这存的key为注解的值,value为类属性名
p.put(field.getAnnotation(ApiModelProperty.class).value(), field.getName());
}
}
return p;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
执行结果:
ps:该方式是通过反射机制实现的:当某注解上的@Retention()的值为RetentionPolicy.RUNTIME时,该注解就可以被反射机制所读取
来看一下@ApiModelProperty注解: