开发工具:Android Studio
首先建一个基础类,我们用来操作的类:如下
package com.example;
public class Person {
private String name;
private String age;
public Person(String name, String age) {
this.name = name;
this.age = age;
System.out.println("有参数的构造器!");
}
public Person() {
System.out.println("无参数的构造器!");
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
具体反射代码的实现步骤,我们通过反射的机制去调用基础类的方法,通过反射去给基础类中的成员变量赋值;
package com.example;
import java.io.File;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectionTest {
//通过Method获取类对象的方法
public Object invoke(String className,String methodName, Object ... args) throws
ClassNotFoundException, NoSuchMethodException,
IllegalAccessException, InstantiationException,
InvocationTargetException {
Class aClass = Class.forName(className);
Class [] parameterTypes = new Class[args.length];
for (int i=0;i<args.length;i++){
parameterTypes[i] = args[i].getClass();
}
Method method = aClass.getDeclaredMethod(methodName,parameterTypes);
method.setAccessible(true);//设置能获取私有方法
Object obj = aClass.newInstance();//获取对象
return method.invoke(obj,args);//执行
}
//通过Field获取类对象的成员变量
public void testFiled(String className,String fieldName,String val) throws
ClassNotFoundException, NoSuchFieldException,
IllegalAccessException, InstantiationException {
Class cAClass = Class.forName(className);
Object obj = null;
Field field = null;
for (Class clazz2 = cAClass ; clazz2 != Object.class;
clazz2 = clazz2.getSuperclass()){
field = cAClass.getDeclaredField(fieldName);
}
obj = cAClass.newInstance();
field.setAccessible(true);
field.set(obj,val);//给成员变量复制
}
}
这是一个单元测试类,用来测试反射代码是否是正确的
package com.example;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class ReflectionTestTest {
@Test
public void testClass() throws Exception {
ReflectionTest reflectionTest = new ReflectionTest();
reflectionTest.invoke("com.example.Person","setAge","12");
reflectionTest.testFiled("com.example.Person","age","112");
}
}