使用反射机制调用构造函数

来源:互联网 发布:手机压缩文件解压软件 编辑:程序博客网 时间:2024/05/16 11:33

先来观察一个类,如下:

package com.andy.entity;public class Cat {        private int age;//定义猫的年龄        private double weight;//定义猫的体重        public Cat(int age,double weight)        {            this.age=age;            this.weight=weight;        }        public Cat() {           System.out.println("-----这是无参构造函数-----------");        }        @Override        public String toString() {                  return "猫的年龄是"+age+"  体重是"+weight;        }}

这是一个普通的java类,需要注意的是该类具有无参构造函数,那么怎么通过反射来获取该类的实例呢?
代码如下:
package com.andy.temp;

public class Temp {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {

    Class<?>class1=Class.forName("com.andy.entity.Cat");    try {        System.out.println(class1);//输出“class com.andy.temp.Cat”        Object  cat=class1.newInstance();        System.out.println(cat);//调用toString方法    } catch (Exception e) {        e.printStackTrace();    }}

}
该程序执行后会输出以下信息:
class com.andy.entity.Cat
—–这是无参构造函数———–
猫的年龄是0 体重是0.0

之所以实例的属性值都是默认值,是因为我们这里调用的是默认构造函数。如果需要调用有参构造函数,那么就需要通过反射机制API获取有参构造函数。
在Class类中,提供了两个和获取构造函数相关的函数,
一是public Constructor<?>[] getConstructors() 该函数用来获得所有的构造函数。
二是public Constructor<T> getConstructor(Class<?>... parameterTypes) 该函数根据参数调用相应的构造函数。
此时保持Cat类不变,将Temp类修改如下:

package com.andy.temp;import java.lang.reflect.Constructor;public class Temp {    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException {        Class<?>class1=Class.forName("com.andy.entity.Cat");        try {            Constructor<?> constructor=class1.getConstructor(int.class,double.class);            Object cat=constructor.newInstance(2,2.6);//相当于正常情况下的new,会调用构造函数            System.out.println(class1);//输出“class com.andy.temp.Cat”            System.out.println(cat);//调用toString方法        } catch (Exception e) {            e.printStackTrace();        }    }}

输出结果如下:
class com.andy.entity.Cat
猫的年龄是2 体重是2.6

建议:在编写类时,要保留无参构造函数

0 0
原创粉丝点击