java – getMethods()返回方法我在实现通用接口时没有定义

前端之家收集整理的这篇文章主要介绍了java – getMethods()返回方法我在实现通用接口时没有定义前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一个简单的界面:
  1. interface Foo {
  2. void myMethod(String arg);
  3. }
  4.  
  5. class FooImpl implements Foo {
  6. void myMethod(String arg){}
  7.  
  8. public static void main(String[] args) {
  9. Class cls = FooImpl.class;
  10. try {
  11. for (Method method : cls.getMethods()) {
  12. System.out.print(method.getName() + "\t");
  13. for(Class paramCls : method.getParameterTypes()){
  14. System.out.print(paramCls.getName() + ",");
  15. }
  16. System.out.println();
  17. }
  18. } catch (SecurityException e) {
  19. // TODO Auto-generated catch block
  20. }
  21. }
  22. }

输出将是:

  1. myMethod java.lang.String,...//Other Method

只打印一个myMethod.

但是如果我将界面更改为通用界面:

  1. interface Foo<T> {
  2. void myMethod(T arg);
  3. }
  4.  
  5. class FooImpl implements Foo<String> {
  6. void myMethod(String arg){}
  7. }

那么奇怪的是输出将是:

  1. myMethod java.lang.Object,myMethod java.lang.String,...//Other Method

为什么在将界面更改为通用接口后,会导致一个带有参数类型Object的方法

解决方法

第一种方法是由编译器创建的 bridge method.
如果您测试“ isBridge()”的方法,您可以过滤掉“错误”的方法(也可以筛选出一些奇异的结果,您可以使用协方差返回).

以下代码不会打印myMethod java.lang.Object:

  1. import java.lang.reflect.Method;
  2.  
  3.  
  4. public class FooImpl implements Foo<String> {
  5. public void myMethod(String arg) {
  6. }
  7.  
  8. public static void main(String[] args) throws Exception {
  9. Class cls = FooImpl.class;
  10. for (Method method : cls.getMethods()) {
  11. if (!method.isBridge()) {
  12. System.out.print(method.getName() + "\t");
  13.  
  14. for (Class paramCls : method.getParameterTypes()) {
  15.  
  16. System.out.print(paramCls.getName() + ",");
  17.  
  18. }
  19. }
  20. System.out.println();
  21. }
  22. }
  23. }
  24.  
  25. interface Foo<T> {
  26. public void myMethod(T arg);
  27. }

猜你在找的Java相关文章