mercredi 4 mai 2016

How to return the name of a specific method with the parameter from a class

I want to return the name of a specific method with the parameter from a class.

I got a program that is also returning the method name but including the class name and package name. The code is:

    import java.lang.reflect.*;

public class ClassDemo {

   public static void main(String[] args) {

     ClassDemo cls = new ClassDemo();
     Class c = cls.getClass();

     try {                
        // parameter type is null
        Method m = c.getMethod("show", null);
        System.out.println("method = " + m.toString());        
     }

     catch(NoSuchMethodException e) {
        System.out.println(e.toString());
     }

     try {
        // method Long
        Class[] cArg = new Class[1];
        cArg[0] = Long.class;
        Method lMethod = c.getMethod("showLong", cArg);
        System.out.println("method = " + lMethod.toString());
     }
     catch(NoSuchMethodException e) {
        System.out.println(e.toString());
     }
   }

   public Integer show() {
      return 1;
   }

   public void showLong(Long l) {
      this.l = l;
   }
   long l = 78655;
} 

And the result is:

method = public java.lang.Integer ClassDemo.show()
method = public void ClassDemo.showLong(java.lang.Long)

My question is there any way where I could get the method name with its associated parameter but without the class name and package name??

I mean in that case the result will be :

method = show()
method = showLong(Long)

I saw the question Getting the name of the current executing method but its not what I want. Can anybody give me any solution??





Aucun commentaire:

Enregistrer un commentaire