3

我希望我的方法“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”的方法?

4

2 回答 2

0

像这样的东西?

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()
于 2013-11-12T03:27:40.563 回答
0

这应该在大多数情况下有效:

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
    }
}
于 2016-03-31T18:34:21.803 回答