创建运行时类的指定
package Reflection3;
import Reflection2.Person;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/*
调用运行时类中指定的结构:属性,方法,构造器
*/
public class ReflectionTest
{
public void testField() throws Exception
{
Class clazz= Person.class;
//创建运行时类的对象
Person person=(Person)clazz.newInstance();
//获取指定的属性:要求运行时类中属性声明为public
//通常不采用此方法
Field id = clazz.getField("id");
/*
//设置当前属性的值
set():参数1:指明设置哪个对象的属性 参数2:将此属性值设置为多少
*/
id.set(person,1001);
/*
获取当前属性的值
get():参数1:获取哪个对象的当前属性值
*/
int pd=(int) id.get(person);
System.out.println(pd);
}
/*
如何操作运行时类中的指定的属性---需要掌握(开发中用这种方法)
*/
public void testField1() throws Exception
{
Class clazz= Person.class;
//创建运行时类的对象
Person person=(Person)clazz.newInstance();
//1.getDeclaredField(String fieldName):获取运行时类中指定变量名的属性
Field name = clazz.getDeclaredField("name");
//2.setAccessible(true):保证当前属性是可访问的
name.setAccessible(true);
//3.获取,设置指定对象的此属性值
name.set(person,"Tom");
System.out.println(name.get(person));
}
/*
如何操作运行时类中的指定的方法---需掌握
*/
public void testtMethod() throws Exception
{
Class clazz= Person.class;
//创建运行时类的对象(静态不需要写)
Person person=(Person)clazz.newInstance();
/*
1. 获取指定的某个方法
getDeclaredMethod(): 参数1:指明获取方法的名称 参数2:指明获取的方法的形参列表
*/
Method show = clazz.getDeclaredMethod("show", String.class);
//2. 保证当前方法是可访问的
show.setAccessible(true);
/*
3. 调用方法的invoke():参数1:方法的调用者 参数2 :给方法形参赋值的实参
invoke()的返回值即为对应类中调用的方法返回值
*/
// show.invoke(person,"CHN");//String nation=porson.show("CHN");
Object