简体   繁体   中英

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. 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. How do I fix so that type.class value = (type.class) cache.get(key) works well? I know this would be a joke for Scala but I want to use Java.

T value = type.cast(cache.get(key));

(您可以很好地声明T类型的变量,但是类型擦除意味着您不能转换为T。幸运的是, Class#cast可以为您提供帮助。)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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