[英]Java instantiate class from string
I have the following, 我有以下内容
public interface SuperbInterface
public class A implements SuperbInterface
public class B extends A
public class C extends B
I want to instantiate C
but I seems to be getting B
, what did I do wrong? 我想实例化C
但是我似乎正在获取B
,我做错了什么?
Class classz = Class.forName("C");
SuperbInterface superb = (SuperbInterface)classz.newInstance();
//Here when I debug it seems to be going to B.doWork() methods instead of C.doWork().
superb.doWork();
The only thing I can think of is that you haven't overridden doWork() in C. 我唯一能想到的是您没有在C中重写doWork() 。
Maybe you have tried ot override but with some spelling mistake in method name or wrong parameters? 也许您尝试过ot覆盖,但是方法名或参数有拼写错误?
Are you sure that C
overrides the doWork
method? 您确定C
会覆盖doWork
方法吗? Based on the question as it is posed it is perfectly reasonable/legal to expect that as part of extending B
, C
does not provide its own implementation for doWork
and instead relies on the one provided the superclass B
. 根据提出的问题,完全有理由/合法地期望,作为扩展B
一部分, C
不会为doWork
提供自己的实现,而是依赖于提供超类B
。
I see the outcome: 我看到了结果:
A's do work A的工作
whats the things you are expecting ? 您期待什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.