我正在开发一个项目(javaFX),其中存在多个bean
类和ViewModel
类,每个bean
类都存在。 A ViewModel
将每个bean
字段映射到Property
字段,我们使用该字段在我们的应用程序中处理/处理数据。 bean
的数据由REST服务检索并且只有在某个地方被引用(否则垃圾回收器会吞下它们)。Singleton-Generic mixin类保存HashMap <ClassName,List <Class objects>:类型安全警告
加载的数据显示在TableView中,取决于搜索条件(=用户输入)。如果处理新的搜索 - 与搜索标准无关 - 先前的TableView数据清空 - 所以垃圾收集器收集所有显示的数据对象。
要一次为多个选定的数据对象(例如人员)启用数据处理,我希望将选定的数据对象存储到静态容器中,以防止它们被垃圾收集器收集。我想出了singleton类 - 但我不想为每个ViewModel类创建一个单例类。
我已阅读多篇文章和关于此的讨论,并决定实施一个singleton类(ContainerUtil
),该类包含任何ViewModel类的ViewModel对象列表的HashMap
列表。该类的String
名称被用作Key
,并且各自的List
被用作其Value
。
我尝试了与Class<?>
和E
不同的实现,但总是有一个类型安全错误,这是我想要阻止的。所以我开始重新考虑我的解决方案,现在我不确定
- 如果这真的是很好的实践吗?
- 如果我在我的代码/思想中丢失了一些重要的东西,可能会阻止我进入未经检查的类型安全警告?
- 如果可能有更好的方法来解决所描述的问题?
任何意见或批评与我的方法是值得欢迎的!
因此,这里是我的代码:
public class ContainerUtil
{
private static final ContainerUtil instance;
private final Map<String, List<?>> instances_map;
/**
* <p>Constructor of Class {@link ContainerUtil}</p>
* <p>Is private to prevent other methods to instantiate this class!</p>
*/
private ContainerUtil()
{
// only a single instance allowed
this.instances_map = new HashMap<>();
}
static
{
// Instantiates the one allowed instance at application start
instance = new ContainerUtil();
}
/**
* @return The one instance of {@link ContainerUtil}
*/
public static ContainerUtil getInstance()
{
return instance;
}
/**
* <p>Creates (if not existing in the {@link #instances_map}) and returns a list (=container) of objects of the given class<p>
* @param containerClass - The class of which a container is needed
*/
public <E> List<E> getContainerForClass(final Class<E> containerClass)
{
if (!instances_map.containsKey(containerClass.getName()))
{
List<E> container = new ArrayList<>();
instances_map.put(containerClass.getName(), container);
}
return (List<E>) instances_map.get(containerClass.getName());
// ^^^^^^^^^ unchecked type safety warning
}
}
P.S:我不太知道是否这个职位更适合代码审查,而不是堆栈溢出 - 如果是这样,请通知我。
容器是否有共同的超类?那么你应该可以使用''和'Map >'。 –
daniu
我曾经执行过,但警告没有解决。 –