本文介绍了如何获取对象构造函数的参数名称(反射)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

假设我以某种方式从另一个类获得了一个对象引用:

Say I somehow got an object reference from an other class:

Object myObj = anObject;

现在我可以得到这个对象的类了:

Now I can get the class of this object:

Class objClass = myObj.getClass();

现在,我可以得到这个类的所有构造函数:

Now, I can get all constructors of this class:

Constructor[] constructors = objClass.getConstructors();

现在,我可以循环每个构造函数:

Now, I can loop every constructor:

if (constructors.length > 0)
{
    for (int i = 0; i < constructors.length; i++)
    {
        System.out.println(constructors[i]);
    }
}

这已经给了我一个很好的构造函数总结,例如一个构造函数 public Test(String paramName) 显示为 public Test(java.lang.String)

This is already giving me a good summary of the constructor, for example a constructor public Test(String paramName) is shown as public Test(java.lang.String)

然而,我想获取参数的名称,而不是给我类类型.在这种情况下是paramName".我该怎么做?我尝试了以下但没有成功:

Instead of giving me the class type however, I want to get the name of the parameter.. in this case "paramName". How would I do that? I tried the following without success:

if (constructors.length > 0)
    {
        for (int iCon = 0; iCon < constructors.length; iCon++)
        {
            Class[] params = constructors[iCon].getParameterTypes();
            if (params.length > 0)
            {
                for (int iPar = 0; iPar < params.length; iPar++)
                {
                    Field fields[] = params[iPar].getDeclaredFields();
                    for (int iFields = 0; iFields < fields.length; iFields++)
                    {
                        String fieldName = fields[i].getName();
                        System.out.println(fieldName);
                    }
                }
            }
        }
    }

不幸的是,这并没有给我预期的结果.谁能告诉我我应该怎么做或者我做错了什么?谢谢!

Unfortunately, this is not giving me the expected result. Could anyone tell me how I should do this or what I am doing wrong? Thanks!

推荐答案

此信息在编译后丢失,在运行时无法检索.

This information is lost after compilation and can't be retrieved at runtime.

这篇关于如何获取对象构造函数的参数名称(反射)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-07 02:47