参考文章:
https://www.jianshu.com/p/607ff4e79a13
https://juejin.im/post/6844903776873086989#heading-32
练习源码
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.Type;
/**
* Member
* java.lang.reflect.Field :对应类变量
* java.lang.reflect.Method :对应类方法
* java.lang.reflect.Constructor :对应类构造函数
*
*
* AccessibleObject
* java.lang.reflect.Method :成员方法,静态方法
* java.lang.reflect.Constructor :构造方法
*/
public class TestReflect {
public static void main(String[] args) {
Class c = null;
Object obj = null;
try {
c = Class.forName("com.example.wifi.Reflect.Cat");
obj = c.getConstructor(String.class, int.class).newInstance("短歌短歌", 1);
/**
* 1,属性:变量,静态变量,静态常量
* getDeclaredField(String name)
* 获取指定的变量(只要是声明的变量都能获得,包括private)
* getField(String name)
* 获取指定的变量(只能获得public的)
* getDeclaredFields()
* 获取所有声明的变量(包括private)
* getFields()
* 获取所有的public变量
*/
//name
Field fieldName = c.getDeclaredField("name");
fieldName.setAccessible(true);//可以访问private修改的变量
String name = (String) fieldName.get(obj);
System.out.println("name : " + name);
fieldName.set(obj, "富力东方");
String name2 = (String) fieldName.get(obj);
System.out.println("name : " + name2);
//TAG1
Field fieldTAG1 = c.getDeclaredField("TAG1");
fieldTAG1.setAccessible(true);
String TAG1 = (String) fieldTAG1.get(null);
System.out.println("TAG1 : " + TAG1);
//TAG2
Field fieldTAG2 = c.getDeclaredField("TAG2");
fieldTAG2.setAccessible(true);
String TAG2 = (String) fieldTAG2.get(obj);
System.out.println("TAG2 : " + TAG2);
/**
* 2,Method
* getDeclaredMethod(String name, Class>... parameterTypes)
* 根据方法名获得指定的方法, 参数name为方法名,参数parameterTypes为方法的参数类型,如 getDeclaredMethod(“eat”, String.class)
* getMethod(String name, Class>... parameterTypes)
* 根据方法名获取指定的public方法,其它同上
* getDeclaredMethods()
* 获取所有声明的方法
* getMethods()
* 获取所有的public方法
*/
//静态方法
Method methodGetTAG = c.getDeclaredMethod("getTAG");
methodGetTAG.setAccessible(true);
String result = (String) methodGetTAG.invoke(null);
System.out.println("getTAG : " + result);
//成员方法
Method methodSetName = c.getDeclaredMethod("setName", String.class);
methodSetName.invoke(obj, "猜猜我是谁");
Method methodGetName = c.getDeclaredMethod("getName");
String getName = (String) methodGetName.invoke(obj);
System.out.println("getName : " + getName);
//3,获取方法的返回值的class和taype
Class classReturnType = methodGetName.getReturnType();
Type getGenericReturnType = methodGetName.getGenericReturnType();
//方法参数的class和type的数组.
Class[] getDeclaringClass = methodSetName.getParameterTypes();
Type[] getParameterTypes = methodSetName.getGenericParameterTypes();
//获取方法参数相关信息
Parameter[] getParameters = methodSetName.getParameters();
for (int i = 0; i < getParameters.length; i++) {
Parameter p = getParameters[i];
p.getType(); //获取参数类型
p.getName(); //获取参数名称,如果编译时未加上`-parameters`,返回的名称形如`argX`, X为参数在方法声明中的位置,从0开始
p.getModifiers(); //获取参数修饰符
p.isNamePresent(); //.class文件中是否保存参数名称, 编译时加上`-parameters`返回true,反之flase
}
System.out.println("是否是可变参数"+methodSetName.isVarArgs()); //判断方法参数是否是可变参数
System.out.println("是否是复合方法"+methodSetName.isSynthetic()); //判断是否是复合方法,个人理解复合方法是编译期间编译器生成的方法,并不是源代码中有的方法
System.out.println("是否是桥接方法"+methodSetName.isBridge()); //判断是否是桥接方法,桥接方法是 JDK 1.5 引入泛型后,为了使Java的泛型方法生成的字节码和 1.5 版本前的字节码相兼容,由编译器自动生成的方法。可以参考
//调用定项参数方法
Method eat = c.getDeclaredMethod("eat", String.class);
eat.invoke(obj, "grass");
//调用不定项参数方法
//不定项参数可以当成数组来处理
Class[] argTypes = new Class[] { String[].class };
Method varargsEat = c.getDeclaredMethod("eat", argTypes);
String[] foods = new String[]{
"grass", "meat","苹果","白菜"
};
varargsEat.invoke(obj, (Object)foods);
/**
* 3,构造方法
* getDeclaredConstructor(Class>... parameterTypes)
* 获取指定构造函数,参数parameterTypes为构造方法的参数类型
* getConstructor(Class>... parameterTypes)
* 获取指定public构造函数,参数parameterTypes为构造方法的参数类型
* getDeclaredConstructors()
* 获取所有声明的构造方法
* getConstructors()
* 获取所有的public构造方法
*/
Constructor constructor = c.getDeclaredConstructor(String.class);//获取私有构造方法
constructor.setAccessible(true);
Animal cat = (Cat) constructor.newInstance("只有一个");
System.out.println("获取名字"+cat.toString());
/**
* 4,数组
*/
Field field = c.getDeclaredField("arryInt");
field.setAccessible(true);
//获取一个变量的类型
Class> cArray = field.getType();
//判断该变量是否为数组
if (cArray.isArray()) {
//获取数组的元素类型
int[] array = (int[]) field.get(obj);
for (int i = 0; i < array.length; i++) {
System.out.println(Array.get(array, i));//读取下标bai2数组du元素zhi
}
}
/**
* 5,枚举
*/
Class classEnum = Class.forName("com.example.wifi.Reflect.StatuEnum");
if (classEnum.isEnum()) {
Object[] objectEnum = classEnum.getEnumConstants();
for (int i = 0; i < objectEnum.length; i++) {
System.out.println("枚举="+objectEnum[i]);
System.out.println("枚举值="+((StatuEnum)objectEnum[i]).s);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
//父类
public class Animal {
private String name;
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Animal : name = " + name + " age = " + age;
}
}
//反射获取的对象类
import java.io.Serializable;
class Cat extends Animal implements Serializable {
private static final String TAG = Cat.class.getSimpleName();
private static String TAG1 = Cat.class.getName();
private final String TAG2 = "lalala";
private int[] arryInt = {1, 2, 3, 4, 5, 6};
private String name;
private int i = new Integer(10);
@Deprecated
public int age;
public Cat() {
super("", 0);
}
private Cat(String name) {
super(name, 0);
this.name = name;
}
public Cat(String name, int age) {
super(name, age);
this.name = name;
this.age = age;
}
public void setName(String names) {
this.name = names;
}
public String getName() {
return name;
}
public void eat(String food) {
System.out.println(TAG + "eat food " + food);
}
public void eat(String... foods) {
StringBuilder s = new StringBuilder();
for (String food : foods) {
s.append(food);
s.append(" ");
}
System.out.println(TAG + "eat food " + s.toString());
}
public void sleep() {
System.out.println(TAG + "sleep");
}
private static String getTAG() {
return TAG;
}
@Override
public String toString() {
return "name = " + name + " age = " + age;
}
}
//枚举
public enum StatuEnum {
START("start"), STOP("stop"), DESTROY("destroy");
StatuEnum(String s) {
this.s = s;
}
String s;
}