开发者

Dependency Injection by type using generics - how does it work?

开发者 https://www.devze.com 2022-12-13 02:18 出处:网络
Using Spring, I can get all beans of a cert开发者_开发技巧ain type that are currently defined using this:

Using Spring, I can get all beans of a cert开发者_开发技巧ain type that are currently defined using this:

@Resource
private List<Foo> allFoos;

How does Spring do this? I thought type information of generics was erased at runtime. So how does Spring know about the type Foo of the list and only inject dependencies of the correct type?

To illustrate: I don't have a bean of type "List" that contains the other beans. Instead, Spring creates that list and adds all beans of the correct type (Foo) to this list and then injects that list.


Not all generic information is lost at runtime:

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");
        }
    }

}

Output:

class java.lang.String
0

精彩评论

暂无评论...
验证码 换一张
取 消