通过反射和使用Class.cast() [英] Cast via reflection and use of Class.cast()
问题描述
我没有成功地试图找出什么是 Class.cast()
做或它可能是有益的,同时我想知道我是否可以以某种方式对象通过反射。
I am unsuccessfully trying to find out what does Class.cast()
do or what it may be good for, in same time I am wondering whether I can somehow cast an object via reflection.
首先我认为类似下面的行可能工作,错误:
First I thought something like lines below might have worked, wrongly:
Object o = "A string";
String str = Class.forName("java.lang.String").cast(object);
但是没有显式强制转换它不起作用。
But without explicit cast it does not work.
那么什么是 cast 方法
类
class好吗?是不是有可能只是用反射来投射对象,所以你找到对象的类,使用 Class.forName
它,并以某种方式投射?
So what is cast
method of Class
class good for? And is it somehow possible just with reflection to cast objects, so you find the object's class, use Class.forName
on it and cast it somehow?
推荐答案
工作原理的例子:
class Favorites {
private Map<Class<?>, Object> map = new HashMap<Class<?>, Object>();
public <T> T get(Class<T> clazz) {
return clazz.cast(map.get(clazz));
}
public <T> void put(Class<T> clazz, T favorite) {
map.put(clazz, favorite);
}
}
您可以这样写:
Favorites favs = new Favorites();
favs.put(String.class, "Hello");
String favoriteString = favs.get(String.class);
您的代码不起作用的原因是Class.forName()返回 Class<?>
,即表示未知类型的类对象。虽然编译器可能推断您的示例中的类型,但它通常不能。考虑:
The reason your code doesn't work is that Class.forName() returns a Class<?>
, i.e. a class object representing an unknown type. While the compiler could possibly infer the type in your example, it can not in general. Consider:
Class.forName(new BufferedReader(System.in).readLine())
这个表达式的类型是什么?显然,编译器不能知道类名在运行时是什么,所以不知道
what's the type of this expression? Clearly the compiler can not know what the class name will be at runtime, so it doesn't know whether
String s = Class.forName(new BufferedReader(System.in).readLine()).cast(o);
是安全的。因此,它请求显式转换。
is safe. Therefore it requests an explicit cast.
这篇关于通过反射和使用Class.cast()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!