Java通过反射技术动态创建对象(有参、无参构造)

 实现类:

package com.ljy;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 
* @ClassName: ConstructorTest
* @Description: 通过反射技术动态创建对象(有参、无参构造)
* @author ljy
* @date 2019年9月12日 上午11:50:48
*
 */
public class ConstructorTest {
	public static void main(String[] args) {
		try {
			Class clazz = Class.forName("com.ljy.Teacher");

			// 获取到指定的构造方法
			Constructor constructor1 = clazz.getConstructor(new Class[]{Integer.class, String.class, String.class});
			// 通过获取到的构造方法创建对象
			Object obj1 = constructor1.newInstance(1,"lisi","男");
			System.out.println(obj1.toString());
			
			// 也可以获取无参构造方法,但是比前面一种难
			Object obj2 = clazz.getConstructor(new Class[]{}).newInstance(new Object[]{});
			obj2 = clazz.getConstructor().newInstance();
			System.out.println(obj2);
				
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
	}
}

 

Teacher类:

package com.ljy;

public class Teacher {
	private Integer id;
	private String name;
	private String sex;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Teacher(Integer id, String name, String sex) {
		super();
		this.id = id;
		this.name = name;
		this.sex = sex;
	}
	public Teacher(String name, String sex) {
		super();
		this.name = name;
		this.sex = sex;
	}
	public Teacher() {
	}
	@Override
	public String toString() {
		return "Teacher [id=" + id + ", name=" + name + ", sex=" + sex + "]";
	}
	
	
}

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我好高冷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值