通过反射和使用 Class.cast() 进行转换 [英] Cast via reflection and use of Class.cast()

查看:13
本文介绍了通过反射和使用 Class.cast() 进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
Java Class.cast() vs. cast operator

我试图找出 Class.cast() 做什么或它可能有什么好处,但没有成功.同时我想知道我是否可以通过反射以某种方式投射一个对象.

I am unsuccessfully trying to find out what Class.cast() does or what it may be good for. At the same time I am wondering whether I can somehow cast an object via reflection.

首先,我认为类似下面几行的内容可能会奏效:

First I thought something like the lines below might work:

Object o = "A string";
String str = Class.forName("java.lang.String").cast(object);

但是如果没有明确的强制转换,它就不起作用.

But without an explicit cast it does not work.

那么Class 类的cast 方法有什么用呢?是否有可能仅仅通过反射来投射对象,所以你找到对象的类,在它上面使用 Class.forName 并以某种方式投射它?

So what is the 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆