简体   繁体   English

如何使用泛型实现ServiceLocator?

[英]How to implement a ServiceLocator with generics?

Having this interface: 具有此界面:

public interface ServiceLocator {
    <T> void setService(Class<T> klass, Factory<T> factory)

    <T> void setConstant(Class<T> klass, T value)

    <T> T getObject(Class<T> klass)

}

How do I implement it? 如何实施? I mean, how I declare the structure data? 我的意思是,如何声明结构数据? Is this right? 这是正确的吗?

private Map<Class, Factory> services = new HashMap<>();
private Map<Class, Object> constants = new HashMap<>();
private Map<Class, Factory> services = new HashMap<>();
private Map<Class, Object> constants = new HashMap<>();

If you wanna use this structures you can declare it like that: 如果要使用此结构,可以这样声明:

private Map<Class<?>, Factory<T>> services = new HashMap<>();
private Map<Class<?>, Object> constants = new HashMap<>();

Remember to put Factory<T> to catch the type. 请记住将Factory<T>放入该类型。 Using Class provides you to use AnyClass.class as Key 使用类可让您将AnyClass.class用作键

Btw you can put all in one Map like private Map<Class<?>, Object> and at the get function cast it if it's a Factory or not ;) 顺便说一句,您可以将所有地图放到一个地图中,例如private Map<Class<?>, Object>并在get函数处将其强制转换为是否为Factory;)

Solution: 解:

private Map<Class<?>, Factory<?>> services = new HashMap<>();
private Map<Class<?>, Object> constants = new HashMap<>();

Adding -Xlint:unchecked directive to the compiler options. -Xlint:unchecked指令添加到编译器选项。 And @SuppressWarnings("unchecked") on the methods where you need it. 然后在需要的方法上使用@SuppressWarnings("unchecked") In my case is on getObject method. 在我的情况下是在getObject方法上。

Guava has an interface intended for a similar purpose: ClassToInstanceMap<B> . Guava具有用于类似目的的接口: ClassToInstanceMap<B> The API is: 该API是:

<T extends B> T getInstance(Class<T> type);
<T extends B> T putInstance(Class<T> type, T value);

Looking at the implementation in MutableClassToInstanceMap.java , we see that it uses a HashMap<Class<? extends B>, B> 查看MutableClassToInstanceMap.java中的实现,我们看到它使用了HashMap<Class<? extends B>, B> HashMap<Class<? extends B>, B> wrapped in a ConstrainedMap . HashMap<Class<? extends B>, B>包装在ConstrainedMap Its MapConstraint uses java.lang.Class.cast() to ensure that all the values in the map are legal instances of their corresponding keys. MapConstraint使用java.lang.Class.cast()来确保映射中的所有值都是其对应键的合法实例。

Since B is often just Object , the implementation's HashMap ends up just being a HashMap<Class<? extends Object>, Object> 由于B通常只是Object ,因此实现的HashMap最终只是HashMap<Class<? extends Object>, Object> HashMap<Class<? extends Object>, Object> . HashMap<Class<? extends Object>, Object>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM