问题:
- 如何根据接口获取所有子类/实现类
- 获取枚举的所有值
- 反射获取扩展属性
处理
引入 reflections 类库
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.12</version>
</dependency>
枚举接口定义
public interface IEnum<T extends Enum> {
int getCode();
String getDesc();
String getName();
IEnum[] enumValues();
}
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class EnumItem {
String name;
int code;
String desc;
}
遍历所有实现类,放入枚举Map
Reflections reflections = new Reflections("com.demo.common.consts.enums");
Set<Class<? extends IEnum>> items = reflections.getSubTypesOf(IEnum.class);
items.forEach(
item -> {
String name = item.getSimpleName();
Object[] objects = item.getEnumConstants();
try {
Method getCodeMethod = item.getMethod("getCode");
Method getNameMethod = item.getMethod("getName");
Method getDescMethod = item.getMethod("getDesc");
Set<EnumItem> enumItems = new HashSet<>();
Arrays.asList(objects).forEach(
obj -> {
try {
enumItems.add(EnumItem.builder()
.code((Integer) getCodeMethod.invoke(obj))
.name((String) getNameMethod.invoke(obj))
.desc((String) getDescMethod.invoke(obj))
.build());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
);
ENUM_MAP.put(name, enumItems);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
);
来源:oschina
链接:https://my.oschina.net/ois/blog/3198341