【问题标题】:Cast type T list to object将类型 T 列表转换为对象
【发布时间】:2020-04-16 11:22:28
【问题描述】:

我有一个采用泛型 T 类型参数的方法。

public<T> void run(List<T> inputs){
 System.out.println((Student) inputs.get(0).getFirstName());

}

我正在尝试在 run 方法中访问 Student 类方法。

但我收到 cannot resolve method 'getFirstName()' 编译错误。

请帮忙!

【问题讨论】:

  • 如果您要转换为Student,那么它不是通用的。顺便说一句,您正在尝试将 getFirstName 的返回值转换为 Student
  • 哦,是的,我现在才意识到。我想访问学生类的方法。我该怎么做?
  • 你的类型转换是错误的。应该是((Student) inputs.get(0)).getFirstName()
  • 另外,你应该做&lt;T extends Student&gt; - 几乎总是如果你在铸造,那么你做错了
  • @siddarth- 我也试过了,仍然无法访问 Student 类方法。

标签: java casting


【解决方案1】:

您使用错误的参考调用 getFirstName() 方法。请查找以下代码。

在 () 中保留这种类型转换 '(Student) inputs.get(0)'。

public<T> void run(List<T> inputs){
 System.out.println( ((Student) inputs.get(0)).getFirstName());

}

【讨论】:

  • 如果list 包含非Student 对象会怎样?
  • 你会得到'ClassCastException'。
  • 如果你有&lt;T extends Student&gt;会发生什么?
  • 无论 List 是否包含非学生对象,你肯定会得到 'ClassCastException'。
  • 您可以通过使用 'instanceof' 检查引用来避免 ClassCastException if(Student instanceof inputs.get(0)) { // 在此处编写逻辑 }
猜你喜欢
  • 2011-05-06
  • 2010-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-01
  • 1970-01-01
相关资源
最近更新 更多