Java反射创建实例 - 极悦
Java面向对象
Java异常
Java数组
Java常用类
Java集合
Java IO流
Java线程
Java反射
Socket编程
Java注解开发
Java GoF设计模式
HashMap
Java内存模型
Java线性表

Java反射创建实例

package com.wkcto.chapter08.demo02;

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

/**
 * 通过反射创建对象(创建实例)
 * 		newInstance()
 * 
 * @author 蛙课网
 *
 */
public class Test01 {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		//1) 创建Class对象
		Class<?> class1 = Person.class;
		
		//2) 直接通过Class对象创建实例,会调用类的无参构造方法,如果没有无参构造,则实例化异常
		Object obj1 = class1.newInstance();
		System.out.println( obj1 );  	//调用对象的toString()	
		
		//3)通过构造方法创建实例
		//3.1 反射构造方法Person(String, int, String)
		Constructor<?> constructor = class1.getConstructor(String.class, int.class, String.class);
		
		//3.2通过构造方法 创建实例, 调用newInstance()方法,传递构造方法的实参
		Object obj2 = constructor.newInstance("lisi", 18,"男");    //new Person("lisi", 18,"男")
		System.out.println( obj2 );
		
		
	}

}
package com.wkcto.chapter08.demo02;

public class Person {
	public String name;
	int age;
	private String gender;
	static String country = "中国";
	
	public Person() {
		System.out.println("Person类的无参构造方法");
	}

	public Person(String name, int age, String gender) {
		System.out.println("Person类的有三个参数的构造方法");
		this.name = name;
		this.age = age;
		this.gender = gender;
	}
	
	public void set(String name, int age, String gender) {
		this.name = name;
		this.age = age;
		this.gender = gender;
	}

	@Override
	public String toString() {
		return "Person [name=" + name + ", age=" + age + ", gender=" + gender + "]";
	}
		
}

 

全部教程