JAVA反射 看视频写的一个例子

时间:2021-01-12 19:24:35
package com.stu.reflection;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
* @author Administrator
* 反射的练习,
* ,
*
*
*/
public class Reflect {

/**
* 反射类的构造方法
*
*/

@Test
public void getRefectClass() throws Exception{
//加载需要反射的类
Class clazz = Class.forName("com.stu.reflection.Wook");
Constructor co = clazz.getConstructor(null);//指定无参数的构造方法
co.newInstance();//调用
Constructor co1 = clazz.getConstructor(String.class,String.class);//指定有参数的构造方法
co1.newInstance("admin","passowrd");//调用 传递参数
//指定被私有化的构造方法,采用getDeclaredConstructor
Constructor co2 = clazz.getDeclaredConstructor(List.class);
co2.setAccessible(true);//强制设置私有的构造方法能够被访问
co2.newInstance(new ArrayList<String>());//调用传参
}

/**
* 反射类的方法
* @throws Exception
*/
@Test
public void getRefectByMethod() throws Exception{
//加载需要反射的类
Wook wk = new Wook();
Class clazz = Class.forName("com.stu.reflection.Wook");
Method mo = clazz.getMethod("loginIn", String.class,String.class);
mo.invoke(wk, "admin","password");

Method mo1 = clazz.getMethod("loginOut", String.class);
mo1.invoke(wk, "admin");
//访问静态方法
Method mo2 = clazz.getDeclaredMethod("saveMethod", null);
mo2.setAccessible(true);
mo2.invoke(wk,null);

}

/**
* 反射类的属性
* @throws Exception
*/
@Test
public void getRefectByField() throws Exception{
Wook wk = new Wook();
Class clazz = Class.forName("com.stu.reflection.Wook");
//clazz.newInstance() 相当于 Wook wk = new Wook();
Field fd1 = clazz.getField("aaa");
fd1.get(wk);

Field fd = clazz.getDeclaredField("username");
fd.setAccessible(true);
System.out.println(fd.getName());

// 循环访问静态方法
Field[] fds = clazz.getDeclaredFields();
for (Field f : fds) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), Wook.class);
Method md = pd.getWriteMethod();
md.invoke(wk, "admin");//给属性复制
}

for (Field f : fds) {
PropertyDescriptor pd = new PropertyDescriptor(f.getName(), Wook.class);
Method md = pd.getReadMethod();//读取属性值
System.out.println(md.invoke(wk));
}
}


}