简体   繁体   English

Java从字符串实例化类

[英]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覆盖,但是方法名或参数有拼写错误?

Assuming you are using a newer version of Java add @Override to the doWork method. 假设您正在使用Java的较新版本,请将@Override添加到doWork方法中。 If you have incorrectly overriden the method the compiler will then let you know. 如果您错误地重写了该方法,则编译器将告知您。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM