java - 使用 Spring 构造子类而无需显式强制转换
问题描述
示例类:
动物.java
public class Animal {
Animal(){
}
}
狗.java
public class Dog extends Animal {
Dog(){
}
}
春天来电
...
// Dog dog = null; // this works
Animal dog = null; // does not work
ApplicationContext appContext = null;
String path = "animal.xml";
try
{
appContext = new FileSystemXmlApplicationContext("/" + path);
GenericBeanFactoryAccessor gbfa = new GenericBeanFactoryAccessor(appContext);
dog = gbfa.getBean("Dog");
dog.init(color);
return dog;
}
catch (Exception e)
{
LOGGER.info("Bean creation failure, error is: " + e);
return new Animal();
}
动物.xml:
<bean id="Animal" class="test.Animal">
</bean>
<bean id="Dog" class="test.Dog" parent="Animal" >
</bean>
为准系统示例道歉,但我对这个特定问题有疑问。Dog 类不能在代码中显式调用,因为它可能存在也可能不存在。如果包存在,我想用 Spring 创建 Dog 类,但如果不存在,则返回动物。
如果我将dog
变量显式声明为Dog
而不是Animal
,则此代码有效。但是,由于代码可能没有Dog
包,我不能这样做。将dog
变量声明为 anAnimal
会在获取 ApplicationContext 时出错。
12 21:01:09.589 [main] INFO - Bean creation failure, error is: org.springframework.beans.factory.CannotLoadBeanClassException:
Cannot find class [test.Dog] for bean with name 'Dog' defined in file [animals.xml];
nested exception is java.lang.ClassNotFoundException: test.Dog
请记住,如果dog
声明为Dog
而不是,则一切正常Animal
,我不明白为什么我会在这里得到一个未找到类的异常。任何帮助将不胜感激。谢谢!
编辑:修正了小写的狗错字
解决方案
推荐阅读
- c# - unity 陀螺仪只读 2 轴
- python - 在神经网络训练期间应该何时调用反向传播算法?
- r - 如何将参数适当地传递给用户定义的函数,其中参数被另一个函数使用,该函数也作为参数传递
- centos - 即使在 CentOS 8 上将 CA 证书添加到信任库后也会出现证书错误
- c - 输入文本字符串,一个参数有多个值
- c++ - 如何让一帧可以切换页面?像网络浏览器
- excel - 返回从单元格到其下方最后一个非空单元格的溢出范围
- java - 使用 JPA 合并两个相似的表
- python - VSCode 中的 Jupyter 笔记本未显示最新的 python 内核列表
- java - “SerializationException: Unknown magic byte”与工作的生产者/消费者