package otherTests;

/**
* 基本类
*
@author Phoebus
*
*/
public class MyClass {

public MyClass(String msg){
System.out.println(
"我是 " + msg);
}

public MyClass(){
System.out.println(
"我是无参数构造函数");
}
}

 

代码
package otherTests;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
* 测试类
*
@author Phoebus
*
*/
public class OtherTestsMain {
public static void main(String[] args) throws IllegalArgumentException,
SecurityException, InstantiationException, IllegalAccessException,
InvocationTargetException, NoSuchMethodException {

//获取所有构造函数
Constructor ctor[] = MyClass.class.getDeclaredConstructors();
for (Constructor constructor : ctor) {
//获取构造函数的参数
Class c[] = constructor.getParameterTypes();
if (c.length == 1) {
MyClass obj
= (MyClass) MyClass.class.getConstructor(c)
.newInstance(
"参数构造函数");
}
else {
//无参数构造 直接newInstance()
MyClass obj = (MyClass) MyClass.class.newInstance();
}
}
}
}