- package com.itheima.fans;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
- public class Demo4 {
- /**
- * 通过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();
- System.out.println(cons.length);
- 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);
-
- }
- }
- class Person{
- private String name;
- private int age;
- public Person() {
- }
- public Person(String name){
- this.name=name;
- }
- public Person(int age){
- this.age=age;
- }
- public Person(String name, int age) {
- this.age=age;
- this.name=name;}
- 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+"]";
- }
- }
复制代码 |