public static Object getObj(Class clazz) throws Exception {
Constructor con = clazz.getConstructor();
return con.newInstance();
}
public static Object getObj(Class clazz, String param) throws Exception {
Constructor con = clazz.getConstructor(String.class);
return con.newInstance(param);
}
public static void getObjMed(Class clazz, String name, String param)
throws Exception {
Constructor con = clazz.getConstructor(String.class);
Method m = clazz.getMethod(name, String.class);
m.invoke(getObj(clazz), param);
}
}
class Bean1 {
private String name = null;
public Bean1() {
}
public Bean1(String name) {
this.name = name;
}
public void message() {
System.out.println(" name is " + this.name);
System.out.println("Hello world!");
}
public void helloworld(String name) {
System.out.println("hi " + name + " ! This is a nice world!");
}
}
运行结果:
name is null
Hello world!
name is HELL FIRE
Hello world!
hi 中国 ! This is a nice world!作者: lipanfeng 时间: 2012-3-12 19:24
Constructor我们可以理解为:封装了某个类中的所有的构造函数的这么一个类。它的功能主要是创建对象,获取属性值和为属性赋值。因为类中包含有参和无参的构造函数,然后根据参数个数和类型创建相应的对象。