• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

非泛型类的Java泛型问题

用户头像
it1352
帮助1

问题说明

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.

谢谢

正确答案

#1

这是您的问题:

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
系列文章
更多 icon
同类精品
更多 icon
继续加载