Reflection反射

来源:互联网 发布:mysql decode 函数 编辑:程序博客网 时间:2024/05/16 17:34

动态获取类的信息以及动态调用对象的方法的功能来自Java语言的反射机制。

Java反射机制主要提供以下功能:

1、在运行时判断任意一个对象所属的类。

2、在运行时构造任意一个类的对象。

3、在运行时判断任意一个类所具有的成员变量和方法。

4、在运行时调用任意一个对象的方法。

 

API java.lang.reflect包

Class类:代表一个类。

Field类:代表类的成员变量(成员变量也称为类的属性)

Method类:代表类的方法。

Constructor类:代表类的构造方法。

Array类:提供了动态创建数组,以及访问问数组的元素的静态方法。

 

Java中无论生成某个类的多少个对象,这些对象都会对应于同一个Class对象。

 简单例子:

package reflection;import java.lang.reflect.Method;public class reflectionTest1 {public static void main(String[] args) throws Exception {Class<?> classType = Class.forName("java.lang.String");Method[] methods = classType.getDeclaredMethods();for(Method method:methods){System.out.println(method);}}}


 反射应用

首先获取Class类对象(代表的类)

(1)用Class类的静态方法forName:Class.forName("java.lang.String");

(2)使用类的.class语法:String.class;

(3)使用对象的getClass()方法:String s = "aa"; Class<?> clazz = s.getClass();

 

使用反射调用方法

package reflection;import java.lang.reflect.Method;public class ReflectionTest2 {public int sum(int param1, int param2){return param1 + param2;}public static void main(String[] args) throws Exception {Class<?> classType = ReflectionTest2.class;Object reflectionTest = classType.newInstance();Method method = classType.getMethod("sum", new Class[]{int.class, int.class});Object result = method.invoke(reflectionTest, new Object[]{1, 2});System.out.println(result);}}


 数组java.reflection.Array反射

package reflection;import java.lang.reflect.Array;public class ArrayTest1 {public static void main(String[] args) throws Exception {Class<?> classType = Class.forName("java.lang.String");Object array = Array.newInstance(classType, 10);Array.set(array, 5, "hello");String str = (String)Array.get(array, 5);System.out.println(str);}}


 

 

 

 

 

 

原创粉丝点击