非泛型类中的Java泛型问题 [英] Trouble with Java generics in non-generic class

查看:83
本文介绍了非泛型类中的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() { }
 }

这篇关于非泛型类中的Java泛型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆