一、通过反射的方式可以获取class对象中的属性、方法、构造函数等
public class MyReflect {
public String className = null;
@SuppressWarnings("rawtypes")
public Class personClass = null;
/**
* 反射Person类
* @throws Exception
*/
@Before
public void init() throws Exception {
className = "cn.zekun_reflect.Person";
personClass = Class.forName(className);
}
/**
*获取某个class文件对象
*/
@Test
public void getClassName() throws Exception {
System.out.println(personClass);
}
/**
*获取某个class文件对象的另一种方式
*/
@Test
public void getClassName2() throws Exception {
System.out.println(Person.class);
}
/**
*创建一个class文件表示的实例对象,底层会调用空参数的构造方法
*/
@Test
public void getNewInstance() throws Exception {
System.out.println(personClass.newInstance());
}
/**
*获取非私有的构造函数
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void getPublicConstructor() throws Exception {
Constructor constructor = personClass.getConstructor(Long.class,String.class);
Person person = (Person)constructor.newInstance(100L,"zhangsan");
System.out.println(person.getId());
System.out.println(person.getName());
}
/**
*获得私有的构造函数
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void getPrivateConstructor() throws Exception {
Constructor con = personClass.getDeclaredConstructor(String.class);
con.se