首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

java 反照机制(一)简单实例

2012-12-24 
java 反射机制(一)简单实例以下是反射机制的一些实例:1,利用反射机制得到类的所有函数import java.lang.re

java 反射机制(一)简单实例
以下是反射机制的一些实例:
1,利用反射机制得到类的所有函数

import java.lang.reflect.Method;/*通过一个参数导出参数所指定的对象的所有方法*/public class DumpMethod {public static void main(String [] args)throws Exception{Class<?> classType = Class.forName("java.util.Stack"); //参数必须是全类名,即包名+类名,如java.lang.IntegerMethod[] methods = classType.getDeclaredMethods();for(int i = 0;i<methods.length;i++){System.out.println(methods[i].toString());}}}

执行结果:
public synchronized java.lang.Object java.util.Stack.pop()
public java.lang.Object java.util.Stack.push(java.lang.Object)
public boolean java.util.Stack.empty()
public synchronized java.lang.Object java.util.Stack.peek()
public synchronized int java.util.Stack.search(java.lang.Object)


2,通过反射机制复制简单的JavaBean对象
import java.lang.reflect.*;public class ReflectTester {public Object copy(Object object) throws Exception {// 获得对象的类型Class classType = object.getClass();System.out.println("Class:" + classType.getName()); //获取类的全名:包名+类名// 通过默认构造方法(没有参数)创建一个新的对象,参数类型为new Class[] {}空,参数值为new Object[] {}空Object objectCopy = classType.getConstructor(new Class[] {}).newInstance(new Object[] {});// 获得对象的所有属性Field fields[] = classType.getDeclaredFields();for (int i = 0; i < fields.length; i++) {Field field = fields[i];String fieldName = field.getName();String firstLetter = fieldName.substring(0, 1).toUpperCase();// 获得和属性对应的getXXX()方法的名字String getMethodName = "get" + firstLetter + fieldName.substring(1);// 获得和属性对应的setXXX()方法的名字String setMethodName = "set" + firstLetter + fieldName.substring(1);//getMethod(String name, Class[] parameterTypes):获得类的特定方法,name 参//数指定方法的名字,parameterTypes参数指定方法的参数类型// 获得和属性对应的getXXX()方法Method getMethod = classType.getMethod(getMethodName,new Class[] {});    // 获得和属性对应的setXXX()方法Method setMethod = classType.getMethod(setMethodName,new Class[] { field.getType() });/*Method类的invoke(Object obj,Object args[])方法用于动态执行一个*对象的特定方法,它的第一个obj 参数指定具有该方法的对象,第二个args 参数指定*向该方法传递的参数。*/// 调用原对象的getXXX()方法Object value = getMethod.invoke(object, new Object[] {});System.out.println(fieldName + ":" + value);// 调用复制对象的setXXX()方法setMethod.invoke(objectCopy, new Object[] { value });}return objectCopy;}public static void main(String[] args) throws Exception {Customer customer = new Customer("Tom", 21);customer.setId(new Long(1));Customer customerCopy = (Customer) new ReflectTester().copy(customer);System.out.println("Copy information:" + customerCopy.getName() + " "+ customerCopy.getAge());}}class Customer { // Customer类是一个JavaBeanprivate 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;}}

执行结果:
Class:reflection.Customer
id:1
name:Tom
age:21
Copy information:Tom 21

3,动态创建对象并获取对象方法,调用对象方法
package reflection;import java.lang.reflect.*;public class InvokeTester {public int add(int param1, int param2) {return param1 + param2;}public String echo(String msg) {return "echo:" + msg;}public static void main(String[] args) throws Exception {Class classType = InvokeTester.class;Object invokeTester = classType.newInstance();// 调用InvokeTester对象的add()方法,add()方法的两个参数为int 类Method addMethod = classType.getMethod("add", new Class[] { int.class,int.class });/* * Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,如果参数 * 为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象, */// 动态调用add()方法Object result = addMethod.invoke(invokeTester, new Object[] {new Integer(100), new Integer(200) });System.out.println((Integer) result);// 调用InvokeTester对象的echo()方法Method echoMethod = classType.getMethod("echo",new Class[] { String.class });result = echoMethod.invoke(invokeTester, new Object[] { "Hello" });System.out.println((String) result);}}

执行结果:
300
echo:Hello

4,利用反射机制动态创建数组对象
package reflection;import java.lang.reflect.Array;//Array属于反射的包中public class ArrayTester {public static void main(String args[]) throws Exception {//用于指定数组的类型Class classType = Class.forName("java.lang.String");// 创建一个长度为10 的字符串数组Object array = Array.newInstance(classType, 10);// 把索引位置为i 的元素设为"hello"ifor (int i = 0; i < 10; i++) {Array.set(array, i, "hello" + i);}for (int i = 0; i < 10; i++) {String current = (String) Array.get(array, i);// 读取索引位置为5 的元素的值System.out.print(current + " ");}}}

执行结果:
hello0 hello1 hello2 hello3 hello4 hello5 hello6 hello7 hello8 hello9

热点排行