用反射机制返回类的所有构造方法

为在运行时拿到类的构造方法,可以通过反射机制去实现。

public Constructor>[] getConstructors()

throws SecurityException;// 该方法在Class类中定义

public final class Constructor

extends AccessibleObject

implements GenericDeclaration, Member;// 构造方法类

—-实例:

package com.mldn;

import .lang.reflect.Constructor;

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)

{

System.out.println(“T的构造方法:” + c1); // 打印构造方法信息; 调用toString()

}

}

}

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类的toString()方法打印构造方法的相关信息

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

T的构造方法:public com.mldn.T()

T的构造方法:public com.mldn.T(.lang.String)

T的构造方法:public com.mldn.T(.lang.String,int)

*/

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

赞赏

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

上一篇
下一篇

相关文章

在线留言

你必须 登录后 才能留言!

在线客服
在线客服 X

售前: 点击这里给我发消息
售后: 点击这里给我发消息

智乐兔官微