【发布时间】:2013-05-17 20:46:14
【问题描述】:
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 代码仍然存在问题。我已经解决了上面代码中遇到的问题。当我尝试编译上面的 codd 时,出现以下错误:
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)
这可能是因为我想用通用的东西做一些他们没有设计做的事情,但根据我对文档的理解,这应该可行。当然,我阅读文档的想法是我可以做这样的事情,这肯定会影响我对它的理解。
谢谢
【问题讨论】:
-
我真的想复制 C++ 模板化成员函数 template
hello(T typ) { } -
如果我理解你的问题,你有两个接口 Foo 和 Bar。两个接口都有一个名为 hello() 的方法。您想创建一个类似 private static
void hello(T typ) 的方法,其中 T 是 Foo 或 Bar。我做对了吗?