一个简单的界面:
interface Foo {
void myMethod(String arg);
}
class FooImpl implements Foo {
void myMethod(String arg){}
public static void main(String[] args) {
Class cls = FooImpl.class;
try {
for (Method method : cls.getMethods()) {
System.out.print(method.getName() + "\t");
for(Class paramCls : method.getParameterTypes()){
System.out.print(paramCls.getName() + ",");
}
System.out.println();
}
} catch (SecurityException e) {
// TODO Auto-generated catch block
}
}
}
输出将是:
myMethod java.lang.String,...//Other Method
只打印一个myMethod.
但是如果我将界面更改为通用界面:
interface Foo<T> {
void myMethod(T arg);
}
class FooImpl implements Foo<String> {
void myMethod(String arg){}
}
那么奇怪的是输出将是:
myMethod java.lang.Object,myMethod java.lang.String,...//Other Method
为什么在将界面更改为通用接口后,会导致一个带有参数类型Object的方法?
解决方法
第一种方法是由编译器创建的
bridge method.
如果您测试“
isBridge()”的方法,您可以过滤掉“错误”的方法(也可以筛选出一些奇异的结果,您可以使用协方差返回).
以下代码不会打印myMethod java.lang.Object:
import java.lang.reflect.Method;
public class FooImpl implements Foo<String> {
public void myMethod(String arg) {
}
public static void main(String[] args) throws Exception {
Class cls = FooImpl.class;
for (Method method : cls.getMethods()) {
if (!method.isBridge()) {
System.out.print(method.getName() + "\t");
for (Class paramCls : method.getParameterTypes()) {
System.out.print(paramCls.getName() + ",");
}
}
System.out.println();
}
}
}
interface Foo<T> {
public void myMethod(T arg);
}
