黑马程序员技术交流社区
标题:
反射基本调取步骤
[打印本页]
作者:
122125241
时间:
2015-7-5 22:34
标题:
反射基本调取步骤
package it.cast;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/*
* 类加载器是专门加载类而存在的
* 根类加载器 扩展类加载器 系统类加载器
* 虚拟机调用根类加载器和扩展类加载器.在我们运行自己写的系统类加载器时
* 反射:
* */
public class Demo {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// 三种方法创建类自解码文件对象
Class<? extends Student> c2 = new Student().getClass();
Class<?> c1 = Class.forName("it.cast.Student");
Class<?> c = Student.class;
System.out.println("--------------------------------------");
// 获取该类公共的单个构造方法与多个构造方法
Constructor<?> constructor2 = c.getConstructor();
Constructor<?>[] constructors = c.getConstructors();
// 获取该类所有的单个构造方法或者多个构造方法
Constructor<?> declaredConstructor = c.getDeclaredConstructor();
Constructor<?>[] declaredConstructors = c.getDeclaredConstructors();
System.out.println("--------------------------------------");
// 通过任意一个构造方法创造对象实例化
Object newInstance = constructor2.newInstance();
System.out.println("--------------------------------------");
// 获取该类的公共的多个成员变量
Field[] fields = c.getFields();
// 获取该类所有的成员变量
// c.getDeclaredField(name);
Field[] declaredFields = c.getDeclaredFields();
// 获取单个成员变量的对象并赋值
// 公共的变量直接赋值
Field field = c.getField("a");
//念法(给newInstance对象的field成员变量赋值为22)
field.set(newInstance, 22);
// 私有变量赋值
Field field2 = c.getDeclaredField("name");
field2.setAccessible(true);
field2.set(newInstance, "张三");
Field field3 = c.getDeclaredField("age");
field3.setAccessible(true);
field3.set(newInstance, 32);
System.out.println("--------------------------------------");
//获取所有的方法
Method[] methods = c.getMethods();//这个获取自己的和父类的所有方法
Method[] methods2 = c.getDeclaredMethods();//获取自己的方法
for (Method method : methods2) {
System.out.println(method);
}
//获取单个方法并调用
Method method = c.getMethod("setAge",int.class);
method.setAccessible(true);
method.invoke(newInstance, 200);
System.out.println(newInstance);
}
}
复制代码
作者:
STRUGGLE
时间:
2015-7-6 10:17
6666666666
作者:
dajiaoya
时间:
2015-7-6 12:51
分线快乐,赞一个
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2