Java中的反射

时间:2014-06-20 09:20:31   收藏:0   阅读:246

Java中的反射机制:

在Java运行时环境中,对于任意一个类,能否知道这个类的哪些属性和方法?对于任意一个对象,能否调用它的任意一个方法?答案是肯定的。这种动态获取类的信息以及动态调用对象的方法的功能来自于Java语言的反射(Reflection)机制。

Java反射机制主要提供了一下功能:
?在运行时判断任意一个对象所属的类;
?在运行时构造任意一个类的对象;
?在运行时判断任意一个类所具有的成员变量和方法;
?在运行时调用任意一个对象的方法。

Reflection是Java被视为动态(准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括modifiers(诸如static、public等等)、superclass(例如Object)、实现interfaces(例如Serializable),也包括fields和methods的所有信息,并可于运行时改变fields内容或调用methods。

一般而言,开发者社群说到动态语言,大致认同一个定义是:程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言。从这个观点看,Perl、Python、Ruby是动态语言,C++、Java、C#不是动态语言。

尽管在这样的定义与分类下Java不是动态语言,它却有着一个非常突出的动态相关机制:Reflection。这个字的意思是“反射、映像、倒影”,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。换句话说,Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods的定义),并生成其对象实体、或对其fields设值、或唤起其methods。这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。Reflection和introspection是常被并提的两个术语。

Java Reflection APIs 简介:
在JDK中,主要由以下类来实现Java反射机制,这些类都位于java.lang.reflect包中
–Class类:代表一个类
–Field类:代表类的成员变量(成员变量也成为类属性)
–Method类:代表类的方法
–Constructor类:代表类的构造方法
–Array类:提供动态创建数组,以及访问数组的元素的静态方法

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

两个例子程序:
import java.lang.reflect.Method;

public class DumpMethods {
	
	public static void main(String[] args) throws Exception{
		
		//Class对象描述了某个特定的类对象
		Class<?> classType = Class.forName("java.lang.String");
		
		//通过反射获取到所有的方法
		Method[] methods = classType.getDeclaredMethods();
		
		//打印所有的方法
		for(Method m : methods){
			System.out.println(m);
		}
	}

}

import java.lang.reflect.Method;

public class InvokeTester {

	public int add(int parm1, int parm2) {
		return parm1 + parm2;
	}

	public String echo(String message) {
		return "hello:" + message;
	}

	public static void main(String[] args) throws Exception {
		// InvokeTester test = new InvokeTester();
		// System.out.println(test.add(1, 2));
		// System.out.println(test.echo("Java"));
		
		Class<?> classType = InvokeTester.class;
		
		//通过反射生成一个InvokeTester类型的对象
		Object o = classType.newInstance();
		
		//通过反射获取到add方法
		Method addMethod = classType.getMethod("add", new Class[] { int.class,
				int.class });
		
		//调用对象的add方法并把参数传进去
		System.out.println(addMethod.invoke(o,new Object[]{1,2}));
		
		//通过反射获取到echo方法
		Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
		
		//调用对象的echo方法并把参数传进去
		System.out.println(echoMethod.invoke(o, new Object[]{"Java"}));
	}
}

要想使用反射,首先需要获得待处理类或对象所对应的Class对象。

获取某个类或对象所对应的Class对象的3种方式:
1)使用Class类的静态方法forName,如Class.forName("java.lang.String");
2)使用.class语法,如String.class;
3)使用对象的getClass方法,如String s = "abc"; Class<?> classType = s.getClass();

若想通过类的不带参数的构造方法来生成对象,我们有两种方式:
1)先获得Class对象,然后通过该Class对象的newInstance方法直接获得即可。如
Class<?> classType = String.class; 
Object o = classType.newInstance();
2)先获得Class对象,然后通过该Class对象获得所对应的Constructor对象,再通过该Constructor对象的newInstance方法生成。如
Class<?> classType = Customer.class;
Constructor constructor  =classType.getConstructor(new Class[]{});
Object o1 = constructor.newInstance(new Object[]{});

若想通过类的带参数的构造方法来生成对象,只能使用下面这种方式:
Class<?> classType = Customer.class;
Constructor constructor2  = classType.getConstructor(new Class[]{String.class,int.class});
Object o2 = constructor.newInstance(new Object[]{"张三",20});

稍完整一点的示例:
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectTest {

	// 该方法实现对Customer的拷贝
	public static Object copy(Object object) throws Exception {
		Class<?> classType = object.getClass();

		Object objectCopy = classType.getConstructor(new Class[] {})
				.newInstance(new Object[] {});

		Field[] fields = classType.getDeclaredFields();

		for (Field field : fields) {
			String name = field.getName();
			String firstLetter = name.substring(0, 1).toUpperCase();// 将属性的首字母转换为大写

			String getMethodName = "get" + firstLetter + name.substring(1);
			String setMethodName = "set" + firstLetter + name.substring(1);

			Method getMethod = classType.getMethod(getMethodName,
					new Class[] {});
			Method setMethod = classType.getMethod(setMethodName,
					new Class[] { field.getType() });

			Object value = getMethod.invoke(object, new Object[] {});

			setMethod.invoke(objectCopy, new Object[] { value });
		}

		return objectCopy;
	}

	public static void main(String[] args) throws Exception {

		Customer c = new Customer("Tom", 20);
		c.setId(1L);
		Object o = copy(c);
		Customer customerCopy = (Customer) o;

		System.out.println(customerCopy.getId() + "," + customerCopy.getName()
				+ "," + customerCopy.getAge());

	}

}

class Customer {
	private long id;
	private String name;
	private int age;

	public Customer() {

	}

	public Customer(String name, int age) {
		this.name = name;
		this.age = age;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

Java.lang.Array类提供了动态创建和访问数组元素的各种静态方法。
第一个示例:
import java.lang.reflect.Array;

public class ArrayTester {
	
	public static void main(String[] args) {
		
		Class<?> classType = String.class;
		
		Object array = Array.newInstance(classType, 10);
		
		Array.set(array, 5, "hello");
		
		String s = (String) Array.get(array, 5);
		
		System.out.println(s);
	}
}

第二个示例:
Integer.TYPE 返回的是int所对应的Class对象
Integer.class 返回的是Integer所对应的Class对象
import java.lang.reflect.Array;

public class ArrayTester2 {
	
	public static void main(String[] args) {
		
		int[] dims = new int[]{5,10,15};
		
		Object array = Array.newInstance(Integer.TYPE, dims);
		
		Object arrayObj = Array.get(array, 3);
		
//		Class<?> classType = arrayObj.getClass().getComponentType();
//		
//		System.out.println(classType);
		
		arrayObj = Array.get(arrayObj, 5);
		
		Array.set(arrayObj, 10, 37);
		
		int[][][] arrayCast = (int[][][]) array;
		
		System.out.println(arrayCast[3][5][10]);
		
	}
	
}


Java中的反射,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!