Java反射:动态创建类实例并将其分配给父对象 [英] Java Reflection: Creating class instance dynamically and assigning it to Parent object

查看:45
本文介绍了Java反射:动态创建类实例并将其分配给父对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String child = "C";
Parent p = null;
try {
    Class c1 = new Class.forName(child);
    Constructor co = c1.getConstructor();
    // p=co.newInstance(null); //This gives compilatoin error cannot
    // conver object to Parent
    // p=(c1.getClass())co.newInstance(null);//also gives cast errror
    p = (Parent) co.newInstance(null);// this works but it typecasts the
    // child to Parent
} catch (Exception e) {
}

我想做什么.

我有多个继承自 Parent 的 Child 类.我正在获取子类名称作为字符串输入.

I have multiple Child classes inherited from Parent. I am getting child class name as string input.

我想实例化 Child 类的对象并将其分配给 Parent.我不想将 Child 类型转换为 Parent.在后面的代码中,我需要比较两个 Child 类.如果我将它类型转换为父级.我无法区分 Child1 和 Child2.

I want to instantiate the object of Child class and assign it to Parent. I do not want to type cast Child to Parent. As later in the code i need to compare two Child classes. If I typecast it to Parent. I cannot differentiate between Child1 and Child2.

推荐答案

类型转换对对象本身绝对没有影响.使用 p = (Parent) t 只是对 t 进行运行时检查,以确保 t 的类型可分配给 Parent(即 t 是一个 Parent 或者它是 Parent 的子类).之后,t 仍将是 Child1 或其 实际 类型.

Typecasting has absolutely no effect on the object itself. Using p = (Parent) t simply does a runtime check on t to make sure that the type of t is assignable to Parent (i.e. either t is-a Parent or it is-a subclass of Parent) . Afterward, t will still be a Child1 or whatever its actual type always has been.

使用显式转换.

这篇关于Java反射:动态创建类实例并将其分配给父对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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