2 回答
TA贡献1982条经验 获得超2个赞
您可以通过使用函数来查看推断的泛型类型getGenericSuperclass,然后再看getActualTypeArguments一个示例:
// Given that all classes in this set are actually subclasses of ClassBase
Set<Class<? extends ClassBase>> classes = Set.of(ClassA.class, ClassB.class, ClassC.class);
System.out.println(classes); // [class test.ClassB, class test.ClassA, class test.ClassC]
@SuppressWarnings("unchecked")
Set<Class<? extends ClassBase<Long>>> result = classes.stream()
.filter(cls -> {
// Get superclass, which is ClassBase, so assume it's also parameterized
ParameterizedType superClass = (ParameterizedType) cls.getGenericSuperclass();
Type inferred = superClass.getActualTypeArguments()[0]; // get first type argument
return inferred == Long.class; // check if it's 'Long'
})
// Can now say they all extend ClassBase<Long>
.map(cls -> (Class<? extends ClassBase<Long>>) cls)
.collect(Collectors.toSet());
System.out.println(result); // [class test.ClassA, class test.ClassB]
您将获得一个Set<Class<? extends ClassBase<Long>>>包含扩展类的ClassBase<Long>。Set<Class<ClassBase<Long>>>您所要求的A ,从技术上讲应该只拥有该类ClassBase本身,而您实际上对子类却很感兴趣,因此您可以得到Class<? extends ClassBase<Long>>。
TA贡献1862条经验 获得超6个赞
对于使用的弹簧人,并将这些类由容器管理(它们标注有一些春天注解喜欢@Service
,@Component
),你可以得到所有用以下方法的类:
@Inject Set <ClassBase <Long>> extensionsWithLongType;
添加回答
举报