java - 如何使用类中的参数返回特定方法的名称

标签 java reflection

我想使用类中的参数返回特定方法的名称。

我有一个程序,它也返回方法名称,但包括类名称和包名称。代码是:

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

结果是:

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

我的问题是,有什么方法可以获取方法名称及其关联参数,但没有类名称和包名称?

我的意思是在这种情况下结果将是:

method = show()
method = showLong(Long)

我看到了问题Getting the name of the current executing method但这不是我想要的。谁能给我任何解决方案吗?

最佳答案

System.out.print(m.getName() + "(");
Class<?>[] params = m.getParameterTypes();
for (int i = 0; i < params.length; i++) {
    if (i > 0) {
        System.out.print(", ");
    }
    System.out.print(params[i].getSimpleName());
}
System.out.println(")");

关于java - 如何使用类中的参数返回特定方法的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37042545/

相关文章:

java - 在具有更新的 Android 版本的设备中重新构建和运行 Android 程序时出错(androidapi 15 rev1 到 api 15 rev2)

java - Mapreduce 中的 HTTPS 请求

java - JAVA 中 API 链接的最佳设计模式

android - 如何检测通知面板是否展开?

c# - 可选参数无法正常工作

reflection - 如何通过类名将对象拆箱成实际对象

java - Android Spinner 不显示 Firebase 实时数据库数据?

java - Libgdx AndroidLauncher 致命异常 ClassNotFoundException

C# 反射树

scala - 如何对泛型类型参数进行模式匹配?