[英]How to use class type passed as parameter to method to define local variables
I have a cache that compartmentalizes by namespace. 我有一个按名称空间划分的缓存。 I would like to use class type to determine which cache to use.
我想使用类类型来确定要使用的缓存。 The following method gives an idea of what I want to accomplish.
以下方法给出了我要完成的想法。 I use the word
cache
loosely. 我宽松地使用“
cache
”一词。 I am more interested in correcting my design pattern so it works. 我对更正我的设计模式使其更感兴趣。
public static DObject getFromCache(String key,Class<T extends DObject> type) {
MyCache cache = getWithName(type.getName());
// ......
type.class value = (type.class) cache.get(key);
// ......
}
where DObject is a naming interface. 其中DObject是命名接口。 How do I fix so that
type.class value = (type.class) cache.get(key)
works well? 如何解决,使
type.class value = (type.class) cache.get(key)
正常工作? I know this would be a joke for Scala but I want to use Java. 我知道这会对Scala开个玩笑,但我想使用Java。
T value = type.cast(cache.get(key));
(您可以很好地声明T类型的变量,但是类型擦除意味着您不能转换为T。幸运的是, Class#cast
可以为您提供帮助。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.