非泛型类的Java泛型问题
问题说明
public class method
{
private static class Foo
{
public void hello() { System.out.println("Foo"); }
}
private static class Bar
{
public void hello() { System.out.println("Bar"); }
}
private static <T> void hello(T typ)
{
typ.hello();
}
public static void main(String args[])
{
Foo foo = new Foo();
Bar bar = new Bar();
hello(foo);
hello(bar);
}
}
我在这里查看了有关泛型的其他问题,但是尽管我在此处看到了所有内容并将其应用于我编写的代码,但我的Java代码仍然有问题.我已经解决了上面代码中的问题.当我尝试编译上面的代码时,出现以下错误:
I've looked at the other questions here regarding generics, but despite everything I've seen there and applied to the code I've written, I'm still having problems with my Java code. I've boiled the problem I'm having to the code above. When I try to compile the codd above, I get the following error:
method.java:15: error: cannot find symbol
typ.hello();
^
symbol: method hello()
location: variable typ of type T
where T is a type-variable:
T extends Object declared in method <T>hello(T)
可能是我正在尝试使用通用语言执行某项操作,而这些操作本来不是设计来执行的,但是基于我对docum3ntation的理解,这应该行得通.当然,在阅读文档时,我会想到可以做这样的事情,这肯定会影响我对此的理解.
It could be that I'm tr6ing to do something with generic that they were not designed to do, but based on my understanding of the docum3ntation, this should work. Of course I read the documentation with the idea that I could do something like this, which certainly may have influenced my understanding of it.
谢谢
正确答案
这是您的问题:
private static <T> void hello(T typ)
T不会扩展任何实现名为"Hello"的方法的东西.
T doesn't extend anything that implements a method named "Hello".
相反,将其替换为
private static <T extends ClassThatHasHello> void hello(T type)
和班级:
public class ClassThatHasHello {
public void hello() { }
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tanhcfijef
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
检查邮件是否发送成功
it1352 07-25 -
Android微调工具-删除当前选择
it1352 06-20 -
希伯来语的空格句子标记化错误
it1352 06-22 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20