java – getMethods()返回方法我在实现通用接口时没有定义
发布时间:2020-11-18 12:15:12 所属栏目:Java 来源:互联网
导读:一个简单的界面: interface Foo { void myMethod(String arg);}class FooImpl implements Foo { void myMethod(String arg){} public static void main(String[] args) { Class cls = FooImpl.class;
|
一个简单的界面: 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);
} (编辑:哈尔滨站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
