3

I want my method "themethod" is referencing "foo", then in a static block, try to get the method "foo" with "getMethod", to which I pass the name of the method and type of the parameters, but "foo "receives as a parameter a type generic, then I know not to give to work. Code:

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
   } 
}

How do I make "theMethod" referencing a method called 'foo'?

  • Type parameters on the class declarations apply only to instance members, not static members. Type parameters in method declarations apply only to that method. – Sotirios Delimanolis Nov 12 '13 at 03:05
  • Have a look at this -> http://stackoverflow.com/questions/3403909/get-generic-type-of-class-at-runtime – Nick Grealy Nov 12 '13 at 03:23

2 Answers2

0

Something like this?

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);

Gives

public java.lang.String java.lang.String.toString()
Nick Grealy
  • 24,216
  • 9
  • 104
  • 119
0

This should work in the most cases:

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
    }
}