java - 将泛型对象作为父子对象中的方法参数传递 - 整数不能转换为 E
问题描述
这是我的情况,我无法让它工作。
public class A<E extends Comparable<E>> {
E e;
void setE(E e1){
e = e1;
}
}
public class main{
public static void main(String[] args){
A<Integer> aObj = new A<Integer>
aObj.setE(some_e); // works perfectly
C cObj = new C();
// this is what I want to do or something similar but it doesnt work because of the failure shown below
cObj.readSomeFileToGetE(aObj);
}
但是我有另一个真正需要设置 E 而不是 main 的类(因为它读取一个文件并且有很多方便的相关代码),它的父子层次结构如下:
public class B{
public <E extends Comparable<E>> void readSomeFileTogetE(A<E>);
}
public class IntB extends B() {
//This derived class will only cater to Integers. Similar sibling classes will cater to Floats, etc.
public <E extends Comparable<E>> void readsomeFileTogetE(A<E> aObj){
//buffered reader defined to read a file that store an integer
String xyz = br.readline();
Integer some_e = Integer.parseInt(xyz);
aObj.setE(some_e); // fails saying Integer cannot be converted to E.
}
}
公共类 FloatB 扩展 B() {
//This derived class will only cater to Floats.
public <E extends Comparable<E>> void readsomeFileTogetE(A<E> aObj){
//buffered reader defined to read a file that store an integer
String xyz = br.readline();
Integer some_e = Float.parseFloat(xyz);
aObj.setE(some_e); // will fail as well.
}
}
本质上,我必须将一个通用对象作为参数传递给子类。
我来自一个 C 编程世界,在那里传递 void 似乎更容易,但在 Java 中,强类型语法使它变得更加困难。
是否可以用 Java 做我计划做的事情?任何帮助表示赞赏。谢谢。
解决方案
推荐阅读
- java - 出现错误 10 后如何让 Google-Sign in 工作?
- java - Firebase 上传监听器永远不会被解雇
- python - 第一次退出应用程序后保存excel文件的问题
- firebase - Firebase 支出和 AdMob 广告
- php - 调用外部程序(postmap)时php exec()返回错误
- laravel - Laravel 5.8 - 保存加密的用户电子邮件
- c++ - 为特定模板值添加成员变量的任何方式?
- if-statement - Else 行中的非法表达
- encoding - 视频编码标准(如 h.264)如何序列化运动预测?
- r - 在 R 中创建多元 QQ 图