使用java中的反射来投射类 [英] Casting a class using reflection in java

查看:103
本文介绍了使用java中的反射来投射类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类。

abstract class A{}

class B extends A{}

class C extends A{}

这样的对象

A a = new B();

我在运行时获取子类的类名。因此,我需要使用反射来创建一个对象。

I get the class name of the subclass at runtime. So, I need to use reflection to create an object.

我已经做到了。

Class<?> klass = Class.forName(className);

现在我无法将此类转换为子类。

Now I am not able to cast this class to the subclass.

我想实现

A a = klass.newInstance(); // returns Object



我想将对象转换为子类( B C ,由运行时决定)

推荐答案

您可以使用泛型来声明

Class<? extends A> klass;

那么你就可以写

A a = klass.newInstance();

但是,由于 Class.forName 类型信息,没有类型推断声明,你会得到unchecked cast警告。这种方法不再只是将第二行的结果向下转换为 A

However, since Class.forName has no type information on your class, and has no type inference declared, you'll be getting "unchecked cast" warnings. This approach is no more typesafe than just downcasting the result of the second line to A.

这篇关于使用java中的反射来投射类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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