本帖最后由 张学东 于 2012-10-27 23:26 编辑
- <p>package com.itheima.fans;</p><p>import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;</p><p>public class Demo4 {</p><p> /**
- * 通过Class调用其他类中的构造函数 (也可以通过这种方式通过Class创建其他类的对象)
- */
- public static void main(String[] args) {
- Class demo=null;
- try {
- demo=Class.forName("com.itheima.fans.Person");
- } catch (ClassNotFoundException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Person per1=null;
- Person per2=null;
- Person per3=null;
- Person per4=null;
- //取得全部的构造函数
- Constructor cons[]=demo.getConstructors();
- try {
- per1=(Person)cons[0].newInstance();
- per2=(Person)cons[1].newInstance("zhangsan");
- per3=(Person)cons[2].newInstance(25);
- per4=(Person)cons[3].newInstance("zhangsan",25);
-
- } catch (IllegalArgumentException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InstantiationException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (InvocationTargetException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- System.out.println(per1);
- System.out.println(per2);
- System.out.println(per3);
- System.out.println(per4);
- </p><p> }</p><p>}
- class Person{
- private String name;
- private int age;
-
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public String toString(){
- return "["+this.name+" "+this.age+"]";
- }
- } 怎么说 角标越界呢?</p>
复制代码 |