通用键/值与相关类型的通用映射 [英] Generic Map of Generic key/values with related types

查看:142
本文介绍了通用键/值与相关类型的通用映射的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用类型,保留自己的版本的地图,这些版本是为以后使用而创建的。实际上,它是一个单例模式,其中每个类型有一个实例。我到目前为止的代码是:

I'm trying to create a generic type that keeps a map of the versions of itself that have been created for later use. Effectively, it's an singleton pattern where there's one instance per type. The code I have so far is:

public class FieldBinder<T> {
    static final Map<Class<? extends Object>,FieldBinder<? extends Object>> instanceMap = 
        new HashMap<Class<? extends Object>,FieldBinder<? extends Object>>();

    private FieldBinder() {}

    synchronized public static <V extends Object> FieldBinder<V> getInstance(Class<V> klass) {
        if(!instanceMap.containsKey(klass)) {
            instanceMap.put(klass, new FieldBinder<V>());
        }
        return (FieldBinder<V>)instanceMap.get(klass);
    }
}

但我还是不确定做正确。感觉像我应该能够指定集合是(Class - > FieldBinder)。事实上,IDE正在警告返回语句只会加强这个想法。

However, I'm still unsure that I'm "doing it right". It feels like I should be able to specify that the collection is (Class -> FieldBinder). The fact that the IDE is warning about the return statement only reinforces this thought.

有更好的方法来处理这个问题吗?

Is there a better way to handle this?

注意:这个问题似乎非常密切相关,但只是远远不够,我不知道如何应用其中的信息到我自己的问题。

Note: This question seems very closely related, but just far enough away that I can't figure out how to apply the information in it to my own problem.

推荐答案

您的实现是正确的。没有更好的做法(如果在代码中有这样的事情是更好的,这是另一个问题..)

Your implementation is correct. There's no "better" way of doing it (if there is such a thing is "better" in code, which is another issue..)

小修订:


  • < V extends Object> 等效于 / code>这是较不冗长的

  • 类< ;? extends Object> 等效于类<?> ,这是较少冗长的

  • @SuppressWarnings(unchecked)注释告诉编译器该转换是安全的

  • <V extends Object> is equivalent to V which is less verbose
  • Class<? extends Object> is equivalent to Class<?> which is less verbose
  • You can use the @SuppressWarnings("unchecked") annotation to tell your compiler that the cast is safe

这篇关于通用键/值与相关类型的通用映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆