How to get parameter names with Java reflection [duplicate]

╄→尐↘猪︶ㄣ 提交于 2019-12-07 08:45:59

问题


How do I get method signatures with Java reflection?

EDIT: I actually need the parameter NAMES not the types of a method.


回答1:


To get the method i of a class C you call C.class.getMethods()[i].toString().

EDIT: Obtaining parameter names is not possible using the reflection API.

But wen you compiled your class with debug information, it is possible to extract the information from bytecode. Spring does it using the ASM bytecode engineering library.

See this answer for further information.




回答2:


http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/reflect/Method.html#toString()

use the toString() method of java.lang.reflect.Method object for the method you are looking for.

If you want to know how to get that method object just use this as a reference:

Method toString = class.forName("java.lang.String").getDeclaredMethod("toString");
System.out.println(toString);



回答3:


import java.lang.reflect.Method;

public class method1 {
    private int f1(Object p, int x) throws NullPointerException
    {
        if (p == null)
            throw new NullPointerException();
        return x;
    }

    public static void main(String args[])
    {
        try {
            Class cls = Class.forName("method1");

            Method methlist[] = cls.getDeclaredMethods();
            for (int i = 0; i < methlist.length; i++) {
                Method m = methlist[i];
                System.out.println("name = " + m.getName());
                System.out.println("decl class = " + m.getDeclaringClass());
                Class pvec[] = m.getParameterTypes();
                for (int j = 0; j < pvec.length; j++)
                    System.out.println("param #" + j + " " + pvec[j]);
                Class evec[] = m.getExceptionTypes();
                for (int j = 0; j < evec.length; j++)
                    System.out.println("exc #" + j + " " + evec[j]);
                System.out.println("return type = " + m.getReturnType());
                System.out.println("-----");
            }
        }
        catch (Throwable e) {
            System.err.println(e);
        }
    }
}


来源:https://stackoverflow.com/questions/9081212/how-to-get-parameter-names-with-java-reflection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!