繁体   English   中英

如何在java中的反射get方法中传递泛型类

[英]How to pass generic class in reflection get method in java

我希望我的方法“themethod”引用“foo”,然后在一个静态块中,尝试使用“getMethod”获取方法“foo”,我传递方法的名称和参数的类型,但是“foo” “作为参数接收类型通用,然后我知道不给工作。 码:

public class Clazz<T> 
{
   static Method theMethod;

   static 
   {
      try
      {
         Class<Clazz> c = Clazz.class;
         theMethod = c.getMethod( "foo", T.class ); // "T.class" Don't work! 
      }
      catch ( Exception e )
      {
      }
   }
   public static <T> void foo ( T element ) 
   {
       // do something
   } 
}

如何使“theMethod”引用一个名为'foo'的方法?

像这样的东西?

import java.lang.reflect.Method

public class Clazz<T> 
{
    static Method theMethod;
    static Class<T> type;

    public Clazz(Class<T> type) {
      this.type = type;
      this.theMethod = type.getMethod("toString");
    }
}

System.out.println(new Clazz(String.class).theMethod);

public java.lang.String java.lang.String.toString()

这应该适用于大多数情况:

public class Clazz<T> {

    static Method theMethod;

    static {
        try {
            Class<Clazz> c = Clazz.class;
            theMethod = c.getDeclaredMethod("foo", Object.class);
        } catch(Exception e) {}
    }

    public static <T> void foo(T element) {
        // do whatever
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM