用反射机制获取构造方法的详细参数

用反射机制、Constructor、Modifier类可以返回构造方法的详细信息:

// Constructor类:

1. public int getModifiers();// 获取当前构造方法的修饰符,public或者protected或者。。。,返回的是个整型!

Returns the language modifiers for the constructor represented by this Constructor object, as an integer. The Modifier class should be used to decode the modifiers.

2. public Class>[] getParameterTypes();// 以数组形式返回当前构造方法的所有参数类型;

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Constructor object. Returns an array of length 0 if the underlying constructor takes no parameters.

3. public String getName();// 获取当前构造方法的名字

Returns the name of this constructor, as a string. This is always the same as the simple name of the constructor's declaring clas    
// Moifier类:

public class Modifier

extends Object;// 类定义:

1. public static String toString(int mod);// 静态方法,将整型值转换为String修饰符;

// Class类:

1.public Constructor>[] getConstructors()

throws SecurityException;

2. public String getName();// 返回该类型完整名字;

—-实例:

package com.mldn;

import .lang.reflect.Constructor;

import .lang.reflect.Modifier; // 修饰符定义类

public class GetConstructors

{

public static void main(String[] args)

{

Class> c = null; // 声明Class对象

try

{

c = Class.forName(“com.mldn.T”); // 获取T类的反射

}

catch (ClassNotFoundException e)

{

e.printStackTrace();

}

Constructor>[] cons = c.getConstructors(); // 取得所有构造方法

for (Constructor> c1 : cons)

{

Class>[] para = c1.getParameterTypes(); // 获取当前构造方法的参数表

System.out.print(“构造方法: “);

int mo = c1.getModifiers(); // 获取当前构造方法的修饰符(访问权限)

System.out.print(Modifier.toString(mo) + ” “);

System.out.print(c1.getName() + “(“); // 打印构造方法名

int i = 0;

for (Class> p : para)

{

System.out.print(p.getName() + ” arg” + i);

if (++i {

System.out.print(“, “); // 若不是最后一个参数打印逗号

}

}

System.out.println(“){…}”); // 换行

}

}

}

class T // 该类肯定继承自Object

{

private String str = null;

private int it = 0;

public T() // 无参构造

{}

public T(String str) // 有参构造

{

this.str = str;

}

public T(String str, int it) // 有参构造

{

this.str = str;

this.it = it;

}

}

/* 这里只是通过Constructor类的方法打印构造方法的详细信息

ubuntu@xu-desktop:~$ com.mldn.GetConstructors

构造方法: public com.mldn.T(){…}

构造方法: public com.mldn.T(.lang.String arg0){…}

构造方法: public com.mldn.T(java.lang.String arg0, int arg1){…}

*/

声明: 除非转自他站(如有侵权,请联系处理)外,本文采用 BY-NC-SA 协议进行授权 | 智乐兔
转载请注明:转自《用反射机制获取构造方法的详细参数
本文地址:https://www.zhiletu.com/archives-140.html
关注公众号:智乐兔

赞赏

wechat pay微信赞赏alipay pay支付宝赞赏

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!