使用Spring,我可以获得当前使用它定义的某种类型的所有bean:
@Resource
private List<Foo> allFoos;
Spring如何做到这一点?我认为泛型的类型信息在运行时被删除了。那么Spring如何知道列表的类型Foo
并且只注入正确类型的依赖项?
为了说明:我没有包含其他bean的“List”类型的bean。相反,Spring创建该列表并将所有正确类型的bean(Foo
)添加到此列表中,然后注入该列表。
答案 0 :(得分:5)
并非所有通用信息都在运行时丢失:
import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
public class Main {
public static List<String> list;
public static void main(String[] args) throws Exception {
Field field = Main.class.getField("list");
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
ParameterizedType pType = (ParameterizedType) type;
Type[] types = pType.getActualTypeArguments();
for (Type t : types) {
System.out.println(t);
}
} else {
System.err.println("not parameterized");
}
}
}
输出:
class java.lang.String