目标类:
代码实现:
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注解:
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/233574.html原文链接:https://javaforall.net