package com.ljr;
import java.util.*;
public class InterfaceUtils {
public static List<Class<?>> getInterfaces(Object obj) {
List<Class<?>> interfaces = new ArrayList<>();
Class<?> clazz = obj.getClass();
while (clazz != null) {
Class<?>[] directInterfaces = clazz.getInterfaces();
interfaces.addAll(Arrays.asList(directInterfaces));//直接接口
for (Class<?> directInterface : directInterfaces) {
interfaces.addAll(getIndirectInterfaces(directInterface));//接口的接口
}
clazz = clazz.getSuperclass();//直接父类和间接父类的接口
}
return interfaces;
}
private static List<Class<?>> getIndirectInterfaces(Class<?> clazz) {
List<Class<?>> indirectInterfaces = new ArrayList<>();
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> interfaceClass : interfaces) {
indirectInterfaces.add(interfaceClass);
indirectInterfaces.addAll(getIndirectInterfaces(interfaceClass));
}
return indirectInterfaces;
}
public static void main(String[] args) {
// 示例用法
Object obj = new LinkedHashMap<>();
List<Class<?>> interfaces = getInterfaces(obj);
for (Class<?> interfaceClass : interfaces) {
System.out.println(interfaceClass.getName());
}
}
}
运行结果:
存在的问题:
该方法可以获取对象的直接接口和间接接口,但是会重复存放。
解决方案:
我们使用了一个HashSet
来存储接口,这样可以自动去重。最后,我们将HashSet
转换为ArrayList
,以便返回一个有序的接口列表。
package com.ljr;
import java.util.*;
public class InterfaceUtils {
public static List<Class<?>> getInterfaces(Object obj) {
//List<Class<?>> interfaces = new ArrayList<>();
Set<Class<?>> interfaces = new HashSet<>();
Class<?> clazz = obj.getClass();
while (clazz != null) {
Class<?>[] directInterfaces = clazz.getInterfaces();
interfaces.addAll(Arrays.asList(directInterfaces));//直接接口
for (Class<?> directInterface : directInterfaces) {
interfaces.addAll(getIndirectInterfaces(directInterface));//接口的接口
}
clazz = clazz.getSuperclass();//直接父类和间接父类的接口
}
return new ArrayList<>(interfaces);
}
private static List<Class<?>> getIndirectInterfaces(Class<?> clazz) {
List<Class<?>> indirectInterfaces = new ArrayList<>();
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> interfaceClass : interfaces) {
indirectInterfaces.add(interfaceClass);
indirectInterfaces.addAll(getIndirectInterfaces(interfaceClass));
}
return indirectInterfaces;
}
public static void main(String[] args) {
// 示例用法
Object obj = new LinkedHashMap<>();
List<Class<?>> interfaces = getInterfaces(obj);
for (Class<?> interfaceClass : interfaces) {
System.out.println(interfaceClass.getName());
}
}
}