欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

使用类的构造函数创建一个实例

程序员文章站 2022-05-23 17:34:00
...
package test;

import java.lang.reflect.Constructor;

public class MyClass {
private String str1;
private String str2;
public MyClass(String s1, String s2){
str1 = s1;
str2 = s2;
}

public static void main(String[] args){

try {
Class[] types= new Class[]{String.class, String.class};
Constructor cons = MyClass.class.getConstructor(types);
Object[] objs = new Object[]{"a", "b"};
MyClass clazz = (MyClass) cons.newInstance(objs);
System.out.println(clazz.toString());
System.out.println(clazz.str1+" , "+clazz.str2);
} catch (Exception e) {
e.printStackTrace();
}

}
}