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

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

文章分类:Java编程

1,利用反射机制得到类的所有函数
Java代码
  1. import  java.lang.reflect.Method;  
  2.   
  3. /*通过一个参数导出参数所指定的对象的所有方法*/   
  4. public   class  DumpMethod {  
  5.       
  6.     public   static   void  main(String [] args) throws  Exception{  
  7.         Class<?> classType = Class.forName("java.util.Stack" );  //参数必须是全类名,即包名+类名,如java.lang.Integer   
  8.           
  9.         Method[] methods = classType.getDeclaredMethods();  
  10.         for ( int  i =  0 ;i<methods.length;i++){  
  11.             System.out.println(methods[i].toString());  
  12.         }  
  13.     }  
  14.       
  15. }  
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.Integer
		
		Method[] 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对象
Java代码
  1. import  java.lang.reflect.*;  
  2.   
  3. public   class  ReflectTester {  
  4.     public  Object copy(Object object)  throws  Exception {  
  5.         // 获得对象的类型   
  6.         Class classType = object.getClass();  
  7.         System.out.println("Class:"  + classType.getName());  //获取类的全名:包名+类名   
  8.         // 通过默认构造方法(没有参数)创建一个新的对象,参数类型为new Class[] {}空,参数值为new Object[] {}空   
  9.         Object objectCopy = classType.getConstructor(new  Class[] {})  
  10.                 .newInstance(new  Object[] {});  
  11.         // 获得对象的所有属性   
  12.         Field fields[] = classType.getDeclaredFields();  
  13.         for  ( int  i =  0 ; i < fields.length; i++) {  
  14.             Field field = fields[i];  
  15.             String fieldName = field.getName();  
  16.             String firstLetter = fieldName.substring(01 ).toUpperCase();  
  17.             // 获得和属性对应的getXXX()方法的名字   
  18.             String getMethodName = "get"  + firstLetter + fieldName.substring( 1 );  
  19.             // 获得和属性对应的setXXX()方法的名字   
  20.             String setMethodName = "set"  + firstLetter + fieldName.substring( 1 );  
  21.               
  22. //          getMethod(String name, Class[] parameterTypes):获得类的特定方法,name 参   
  23. //          数指定方法的名字,parameterTypes参数指定方法的参数类型     
  24.               
  25.             // 获得和属性对应的getXXX()方法   
  26.             Method getMethod = classType.getMethod(getMethodName,  
  27.                     new  Class[] {});      
  28.   
  29.               
  30.               
  31.             // 获得和属性对应的setXXX()方法   
  32.             Method setMethod = classType.getMethod(setMethodName,  
  33.                     new  Class[] { field.getType() });  
  34.               
  35.               
  36. /*          Method类的invoke(Object obj,Object args[])方法用于动态执行一个  
  37. *           对象的特定方法,它的第一个obj 参数指定具有该方法的对象,第二个args 参数指定  
  38. *           向该方法传递的参数。  
  39. */             
  40.             // 调用原对象的getXXX()方法   
  41.             Object value = getMethod.invoke(object, new  Object[] {});  
  42.             System.out.println(fieldName + ":"  + value);  
  43.             // 调用复制对象的setXXX()方法   
  44.             setMethod.invoke(objectCopy, new  Object[] { value });  
  45.         }  
  46.         return  objectCopy;  
  47.     }  
  48.   
  49.     public   static   void  main(String[] args)  throws  Exception {  
  50.         Customer customer = new  Customer( "Tom"21 );  
  51.         customer.setId(new  Long( 1 ));  
  52.         Customer customerCopy = (Customer) new  ReflectTester().copy(customer);  
  53.         System.out.println("Copy information:"  + customerCopy.getName() +  " "   
  54.                 + customerCopy.getAge());  
  55.     }  
  56. }  
  57.   
  58. class  Customer {  // Customer类是一个JavaBean   
  59.     private  Long id;  
  60.     private  String name;  
  61.     private   int  age;  
  62.   
  63.     public  Customer() {  
  64.     }  
  65.   
  66.     public  Customer(String name,  int  age) {  
  67.         this .name = name;  
  68.         this .age = age;  
  69.     }  
  70.   
  71.     public  Long getId() {  
  72.         return  id;  
  73.     }  
  74.   
  75.     public   void  setId(Long id) {  
  76.         this .id = id;  
  77.     }  
  78.   
  79.     public  String getName() {  
  80.         return  name;  
  81.     }  
  82.   
  83.     public   void  setName(String name) {  
  84.         this .name = name;  
  85.     }  
  86.   
  87.     public   int  getAge() {  
  88.         return  age;  
  89.     }  
  90.   
  91.     public   void  setAge( int  age) {  
  92.         this .age = age;  
  93.     }  
  94. }  
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类是一个JavaBean
	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;
	}
}

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

3,动态创建对象并获取对象方法,调用对象方法
Java代码
  1. package  reflection;  
  2.   
  3. import  java.lang.reflect.*;  
  4.   
  5. public   class  InvokeTester {  
  6.     public   int  add( int  param1,  int  param2) {  
  7.         return  param1 + param2;  
  8.     }  
  9.   
  10.     public  String echo(String msg) {  
  11.         return   "echo:"  + msg;  
  12.     }  
  13.   
  14.     public   static   void  main(String[] args)  throws  Exception {  
  15.         Class classType = InvokeTester.class ;  
  16.         Object invokeTester = classType.newInstance();  
  17.   
  18.         // 调用InvokeTester对象的add()方法,add()方法的两个参数为int 类   
  19.         Method addMethod = classType.getMethod("add"new  Class[] {  int . class ,  
  20.                 int . class  });  
  21.   
  22.         /*  
  23.          * Method类的invoke(Object obj,Object args[])方法接收的参数必须为对象,如果参数  
  24.          * 为基本类型数据,必须转换为相应的包装类型的对象。invoke()方法的返回值总是对象,  
  25.          */   
  26.         // 动态调用add()方法   
  27.         Object result = addMethod.invoke(invokeTester, new  Object[] {  
  28.                 new  Integer( 100 ),  new  Integer( 200 ) });  
  29.         System.out.println((Integer) result);  
  30.         // 调用InvokeTester对象的echo()方法   
  31.         Method echoMethod = classType.getMethod("echo" ,  
  32.                 new  Class[] { String. class  });  
  33.         result = echoMethod.invoke(invokeTester, new  Object[] {  "Hello"  });  
  34.         System.out.println((String) result);  
  35.     }  
  36. }  
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,利用反射机制动态创建数组对象
Java代码
  1. package  reflection;  
  2.   
  3. import  java.lang.reflect.Array;  
  4.   
  5. //Array属于反射的包中   
  6. public   class  ArrayTester {  
  7.     public   static   void  main(String args[])  throws  Exception {  
  8. //用于指定数组的类型        
  9. Class classType = Class.forName("java.lang.String" );  
  10.         // 创建一个长度为10 的字符串数组   
  11.         Object array = Array.newInstance(classType, 10 );  
  12.   
  13.         // 把索引位置为i 的元素设为"hello"i   
  14.         for  ( int  i =  0 ; i <  10 ; i++) {  
  15.             Array.set(array, i, "hello"  + i);  
  16.         }  
  17.         for  ( int  i =  0 ; i <  10 ; i++) {  
  18.             String current = (String) Array.get(array, i);// 读取索引位置为5 的元素的值   
  19.             System.out.print(current + " " );  
  20.         }  
  21.   
  22.     }  
  23. }  
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"i
		for (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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值