- package com.day09;
- import java.util.List;
- import java.lang.reflect.Constructor;
- import java.util.ArrayList;
- import org.junit.Test;
- /**
- * 放射就是加载类,并解剖出类的各个组成部分 类的组成部分: 1.构造方法:创建对象 2.属性字段:封装数据 3.属性方法:封装功能
- *
- * @author Administrator
- *
- */
- public class ReflectDemo {
- @Test
- public void
- testLoadClass()
- throws ClassNotFoundException {
- // 获取字节码类,可以采用一下三种方法
- // 相当于加载Person.class文件加入到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- Class clazz1
- =
- new Person().getClass();
- Class clazz2
- = Person.
- class;
- }
- /**
- * public Person() 反射无参构造方法
- *
- * @throws Exception
- */
- @Test
- public void
- reflectConstructNoParameter()
- throws Exception {
- // 将person类加载到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- // 传入参数,获取对应的构造函数
- Constructor personCon = clazz.getConstructor(
- null);
- // 传入参数开始创建对象
- Person p = (Person) personCon.newInstance(
- null);
- }
- /**
- * 反射带有一个参数构造方法构造方法 public Person(String name)
- *
- * @throws Exception
- */
- @Test
- public void
- reflectConstructOneParameter()
- throws Exception {
- // 将person类加载到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- // 传入参数,获取对应的构造函数,这里面要传入一个参数类型,来获取对应参数的构造方法
- Constructor personCon = clazz.getConstructor(String.
- class);
- // 传入参数开始创建对象
- Person p = (Person) personCon.newInstance("zhangsan"
- );
- }
- /**
- * 反射带有多个参数构造方法构造方法 Person(String name, int password)
- *
- * @throws Exception
- */
- @Test
- public void
- reflectConstructManyParameter()
- throws Exception {
- // 将person类加载到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- // 传入参数,获取对应的构造函数,这里面要传入一个参数类型,来获取对应参数的构造方法
- Constructor personCon = clazz.getConstructor(String.
- class
- ,
- int
- .
- class);
- // 传入参数开始创建对象
- Person p = (Person) personCon.newInstance("zhangsan", 23
- );
- }
- /**
- * 反射私有的构造方法构造方法 private Person(List list)
- *
- * @throws Exception
- */
- @Test
- public void
- reflectPrivateConstruct()
- throws Exception {
- // 将person类加载到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- // 传入参数,获取对应的构造函数,这里面要传入一个参数类型,来获取对应参数的构造方法
- // 这里因为该构造方法是私有的,所以用用getDeclaredConstructor才能获得构造方法对象
- Constructor personCon = clazz.getDeclaredConstructor(List.
- class);
- // 要使用私有的属性成员,还需要放开权限,设为可见
- personCon.setAccessible(
- true);
- // 传入参数开始创建对象
- Person p = (Person) personCon.newInstance(
- new ArrayList());
- }
- /**
- * 通过class类,可以直接通过无参的构造方法创建对象
- *
- * @throws Exception
- */
- @Test
- public void
- testNewObj()
- throws Exception {
- // 将person类加载到内存中
- Class clazz = Class.forName("com.day09.Person"
- );
- Person p
- =
- (Person) clazz.newInstance();
- }
- }
来源: http://www.bubuko.com/infodetail-2148900.html