import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* 反射就是在运行时才知道要操作的类是什么,并且可以在运行时获取类的完整构造,并调用对应的方法。
* @author xrn1997
* @date 2021/7/22
*/
public class ReflectTest {
public static void main(String[] args) {
try {
//获取反射
Class<?> reflectClass = Class.forName("edu.ysu.reflection.People");
// 调用1个参数的私有构造方法,私有属性必须setAccessible为true
Constructor<?> constructor2 = reflectClass.getDeclaredConstructor(String.class);
constructor2.setAccessible(true);
constructor2.newInstance("Xiao Ming");
// 调用2个参数的公有构造方法
Constructor<?> constructor1 = reflectClass.getDeclaredConstructor(int.class, String.class);
constructor1.newInstance(24, "Xiao Ming");
//调用1个参数的公有静态成员方法,静态成员不依附实例。
Method staticMethod=reflectClass.getDeclaredMethod("hello",String.class);
Object[] words = {"Welcome 403 !"};
staticMethod.invoke(null ,words);
//调用1个参数的私有成员方法
Method method = reflectClass.getDeclaredMethod("welcome", String.class);
method.setAccessible(true);
//为了使用成员方法需要获得实例,这里使用了无参数的公有构造方法。
Constructor<?> constructor3 = reflectClass.getDeclaredConstructor();
Object newInstance = constructor3.newInstance();
Object[] tips = {"Welcome YSU !"};
method.invoke(newInstance, tips);
//修改成员变量
Field field = reflectClass.getDeclaredField("name");
field.setAccessible(true);
field.set(newInstance,"Da Ming");
System.out.println(field.get(newInstance));
//非常神奇的双反射(用于欺骗Android反射限制),因为我不知道怎么限制反射权限,所以实际上使用普通的反射也能调用这个方法。
Method forName = Class.class.getDeclaredMethod("forName", String.class);
Method getDeclaredMethod = Class.class.getDeclaredMethod("getDeclaredMethod", String.class, Class[].class);
Class<?> secretClass =(Class<?>) forName.invoke(null,"edu.ysu.reflection.Secret");
Method hiddenMethod = (Method) getDeclaredMethod.invoke(secretClass, "showSecret", null);
hiddenMethod.setAccessible(true);
hiddenMethod.invoke(secretClass.getDeclaredConstructor().newInstance());
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
IllegalAccessException | ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
}
}
}
/**
* @author xrn1997
* @date 2021/7/23
*/
class Secret {
private void showSecret(){
System.out.println("这是个秘密,正常人不应该知道");
}
}
/**
* 反射测试所需的类
* @author xrn1997
* @date 2021/7/22
*/
public class People {
private int age;
private String name;
public People(int age) {
this.age = age;
}
public People(int age, String name) {
this.age = age;
this.name = name;
System.out.println("My Name is " + name + ", I'm " + age + " years old.");
}
private People(String name) {
this.name = name;
System.out.println("My Name is " + name + ".");
}
public People() {
}
/**
* 私有成员方法
*
* @param tips 需要打印的字符串
*/
private void welcome(String tips) {
System.out.println(tips);
}
/**
* 静态成员方法
*
* @param words 需要打印的字符串
*/
public static void hello(String words) {
System.out.println(words);
}
}
注:代码中的包名还请根据实际情况自行修改。