[英]Java reflection/generics
public static <T> T inCache(T obj) throws ClassNotFoundException {
String[] token = validateCookie(); //gives me to strings
if (token == null)
return null;
if (Cache.get(token[0]) != null) {
if (Cache.get(token[0]).getClass() == Class.forName(token[1])
&& obj.getClass() == Cache.get(token[0]).getClass()) {
T test = (T) Cache.get(token[0]);
return test;
}
}
return null;
}
The code above is completely wrong. 上面的代码是完全错误的。
Basicly I want to do something like this: 基本上我想做这样的事情:
inCache<User>();
例如inCache<User>();
check if the object that i get out of my cache has the same class that i have specified before. 检查我从缓存中取出的对象是否具有我之前指定的相同类。 (obj.getClass == User.class)
If the classes matches , cast the object to the class and return it. 如果类匹配,则将对象强制转换为类并返回。 return (User)obj
I want to use it like this. 我想这样使用。
User user = inCache<User>();
As for the class signature, why don't you use something like this: 至于类签名,为什么不使用这样的东西:
public static <T> T inCache(Class<T> clazz) throws ClassNotFoundException {
...
}
And then call it like this: 然后这样称呼它:
User user = inCache(User.class);
Generics can't be used the way you described ( User user = inCache<User>();
) due to type erasure at runtime, ie the type of T
is unknown at runtime in that case. 由于在运行时进行类型擦除,因此无法按您描述的方式使用泛型( User user = inCache<User>();
),即在这种情况下, T
的类型在运行时未知。
Also note that it might be better to test using Class#isAssignableFrom(...)
to be able to check for subclasses as well, eg clazz.isAssignableFrom(Cache.get(token[0]).getClass())
. 另请注意,最好使用Class#isAssignableFrom(...)
进行测试,以能够检查子类,例如clazz.isAssignableFrom(Cache.get(token[0]).getClass())
。 That way you could pass an interface or super class and still get a match if the object is of a subtype. 这样,您可以传递接口或超类,并且如果对象属于子类型,则仍会获得匹配项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.