基本概念
在java 运行环境中,对于任意一个类可以获取该类的属性,方法,这种动态的获取类的信息的机制称为反射机制。
java 反射机制 主要提供了一下好处:
- 在运行时判断一个对象所属的类
- 在运行时构造任意一个对象
- 在运行时判断任意一个类所具有的属性和方法
- 在运行时调用对象的任意一个方法
Reflection 是java 被视为动态语言的重要特性之一。
Java Reflection API简介
在JDK中,主要由以下类来实现Java反射机制,这些类(除了第一个)都位于java.lang.reflect包中
Class类:代表一个类,位于java.lang包下。
Field类:代表类的成员变量(成员变量也称为类的属性)。
Method类:代表类的方法。
Constructor类:代表类的构造方法。
Array类:提供了动态创建数组,以及访问数组的元素的静态方法。
Class对象
Java中 ,JVM中同一个类的所有对象都对应与唯一一个 Class 对象
这个 Class 对象是JVM生成的,通过 他可以洞悉类的结构
使用 反射,首先要获取类对应的Class对象
获取Class对象的三种方式
1. className.class 比如 String.class
2. Class.forName(“java.lang.String”)
3. getClass() ,比如 String s=”wjf”;
Class c=s.getClass();
例子一:获取方法名
// 通过 反射 获取方法
Class<?> c=Class.forName("java.lang.String");
Method[] methods=c.getDeclaredMethods();
for(Method m:methods){
System.out.println(m.getName());
}
例子二:通过反射调用方法
import java.lang.reflect.Method;
public class TestReflection {
public void add(int a,int b){
System.out.println(a+b);
}
public void getString(String s){
System.out.println(s);
}
public static void main(String[] args) throws InstantiationException, ReflectiveOperationException{
// 常规执行手段
TestReflection obj=new TestReflection();
obj.add(1, 2);
// 通过 反射方法
// 首先获取 Class对象
Class<?> c=TestReflection.class;
// 生成对象 用 newInstance()
Object reflection=c.newInstance();
System.out.println(reflection instanceof TestReflection);// 输出 true
// 调用method
// 首先获得 与该 方法对应的method对象
Method method=c.getMethod("add", new Class[]{int.class,int.class});
method.invoke(reflection, new Object[]{1,3});
Method method2=c.getMethod("getString", new Class[]{String.class});
method2.invoke(reflection, new Object[]{"wangjianfei"});
}
}