问题
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);
}
}
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)
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.
Thanks
回答1:
Here's your problem:
private static <T> void hello(T typ)
T doesn't extend anything that implements a method named "Hello".
Instead, replace it with
private static <T extends ClassThatHasHello> void hello(T type)
and the class:
public class ClassThatHasHello {
public void hello() { }
}
回答2:
You defined T as subtype of Object. without any type restriction. Object has no hello() method
You could create an interface or super type for the Foo and Bar Then <T extends SuperType>
回答3:
You need to use an interface. This works:
private interface Hello {
public void hello();
}
private static class Foo implements Hello {
@Override
public void hello() {
System.out.println("Foo");
}
}
private static class Bar implements Hello {
@Override
public void hello() {
System.out.println("Bar");
}
}
private static <T extends Hello> void hello(T typ) {
typ.hello();
}
public static void main(String args[]) {
Foo foo = new Foo();
Bar bar = new Bar();
hello(foo);
hello(bar);
}
回答4:
you are using generics, and you are trying to call the hello method of type T, but you dont know what type is that. if you are sure it has hello method, use casting
来源:https://stackoverflow.com/questions/16617622/trouble-with-java-generics-in-non-generic-class