在泛型类型中使用方法
Use methods inside a generic type
考虑这个class:
public class A {
public void method_a(){
System.out.println("THIS IS IT");
}
}
我想在另一个使用通用类型的函数中使用 'method_a' 来获得 class A。
例如:
public class B {
public void calling_this(){
A = new A();
method_b(A);
}
public <T> void method_b(T m){
m.method_a();
}
}
我在 m.method_a()
上收到错误 "cannot find symbol"。
这种方法可行还是有类似的方法?
使用泛型你可以设置一些限制
interface HasMethodA {
void method_a();
}
...
class ... {
<T extends HasMethodA> ... (..., T hasMethodA, ...) {
...
hasMethodA.method_a();
...
}
}
将您的方法定义为
public <T extends A> void method_b(T m){
m.method_a();
}
When do Java generics require <? extends T> instead of <T> and is there any downside of switching?
考虑这个class:
public class A {
public void method_a(){
System.out.println("THIS IS IT");
}
}
我想在另一个使用通用类型的函数中使用 'method_a' 来获得 class A。 例如:
public class B {
public void calling_this(){
A = new A();
method_b(A);
}
public <T> void method_b(T m){
m.method_a();
}
}
我在 m.method_a()
上收到错误 "cannot find symbol"。
这种方法可行还是有类似的方法?
使用泛型你可以设置一些限制
interface HasMethodA {
void method_a();
}
...
class ... {
<T extends HasMethodA> ... (..., T hasMethodA, ...) {
...
hasMethodA.method_a();
...
}
}
将您的方法定义为
public <T extends A> void method_b(T m){
m.method_a();
}
When do Java generics require <? extends T> instead of <T> and is there any downside of switching?