package com.practice;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectDemo {
public static void main(String[] args) throws Exception {
//获取Student 字节码对象
Class clazz =Class.forName("com.practice.Student");
//获取无参构造
Constructor c =clazz.getConstructor();
//创建对象实例
Object obj= c.newInstance();
System.out.println(obj);
/*
调用无参方法
Method method =clazz.getDeclaredMethod("run");
method.invoke(obj);*/
Method method =clazz.getDeclaredMethod("run1",String.class,int.class);
method.invoke(obj,"gujh",11);
//获取值修改参数
//暴力访问
Field f = clazz.getDeclaredField("name");
//值为true则指示反射的对象在使用时应该取消Java语言访问检查
f.setAccessible(true);
f.set(obj,"刘亦菲");
System.out.println(obj);
}
}
|
|