java语言的反射机制1

java语言的反射机制为是java语言所提供的一项特别吸引人的地方,利用反射我们可以对程序的运行进行动态的监控,开发使用反射特性的程序需要使用一些专门的工具类,这些工具类位于java.lang.reflect包中。

1.Class类简介

    Class类属于java.lang包中,不需要使用import语句的引入就可以直接使用,其对象代表一个类,并携带类的一些信息,主要包含构造器,方法和成员变量。

   注:a.java程序在运行的过程中,每个类加载后都在内存中产生一个对应的Class对象,一般来说,这个对象由系统来自动维护,不需要程序开发人员关心,

        b.这里的Class中的“C”为大写,如果变成小写就声明成java的关键字了
下面首先通过一个列子来说明反射机制的使用

Java代码 复制代码
  1. package com;   
  2. import java.lang.reflect.Method;   
  3. public class ReflectTest {   
  4.     Method method [];   
  5.     public ReflectTest(){   
  6.         try{   
  7.         Class c=Class.forName("com.ReflectTest");   
  8.         method=c.getMethods();   
  9.         }catch(ClassNotFoundException e){   
  10.             e.printStackTrace();   
  11.         }   
  12.         if(method.length>0){   
  13.             for(int i=0;i<method.length;i++){   
  14.                 System.out.println(method[i]);   
  15.             }   
  16.         }   
  17.     }   
  18.     public static void main(String args []){   
  19.     new ReflectTest();   
  20.     }   
  21. }  
package com;
import java.lang.reflect.Method;
public class ReflectTest {
	Method method [];
	public ReflectTest(){
		try{
		Class c=Class.forName("com.ReflectTest");
		method=c.getMethods();
		}catch(ClassNotFoundException e){
			e.printStackTrace();
		}
		if(method.length>0){
			for(int i=0;i<method.length;i++){
				System.out.println(method[i]);
			}
		}
	}
	public static void main(String args []){
	new ReflectTest();
	}
}

 这个例子就介绍了反射机制的一些简单的使用方法,首先Class.forName(String)获得一个类的信息,然后就可以对这个类的构造器,方法和成员变量等进行反射了,注意的是:forName(String)中的字符串必须是类完整路径,否则会出现ClassNotFoundException的异常。

 

 另外,由于java中的数组是对象,因此数组对象也可以调用getClass()方法获取对应类的Class对象。 

 

 

 

 

 

Java代码 复制代码
  1. public class ArrayReflection {   
  2.         public ArrayReflection(){   
  3.         String []stringArray=new String[4];   
  4.         int[][]intArray=new int[4][4];   
  5.         Class sc=stringArray.getClass();   
  6.         Class ic=intArray.getClass();   
  7.         System.out.println("一维string数组对应的类名为<SPAN style="COLOR: #000000">:"+</SPAN>sc.getName());   
  8.         System.out.println("二维int数组对应的类名为:"+ic.getName());   
  9.     }   
  10.     public static void main(String args []){   
  11.         new ArrayReflection();   
  12.     }   
  13.   
  14. }   
  15. //运行结果为:   
  16. 一维string数组对应的类名为:[Ljava.lang.String;   
  17. 二维int数组对应的类名为:[[I  
public class ArrayReflection {
		public ArrayReflection(){
		String []stringArray=new String[4];
		int[][]intArray=new int[4][4];
		Class sc=stringArray.getClass();
		Class ic=intArray.getClass();
		System.out.println("一维string数组对应的类名为:"+sc.getName());
		System.out.println("二维int数组对应的类名为:"+ic.getName());
	}
	public static void main(String args []){
		new ArrayReflection();
	}

}
//运行结果为:
一维string数组对应的类名为:[Ljava.lang.String;
二维int数组对应的类名为:[[I

 从运进结果我们可以看出,数组对象也有对应的类,"["表示数组,两个就表示二维数组。

在java中,每种基本数据类型都有对应的代号,对于int----I,boolean---Z,byte--B,char--C,long---J.可以到java网站查询详情

2.Field类的简单介绍

  Field类的对象代表成员变量,携带的是成员变量的一些信息,需要注意的是,与Class类相似,Field对象不能通过构造方法的形式来创建对象,必须通过Class类提供的get方法来获得。

Java代码 复制代码
  1. import java.lang.reflect.Field;   
  2. public class FieldReflectTest {   
  3.     public static void main(String args []){   
  4.         try{   
  5.             Student stu=new Student(21,2003,true,"tom");   
  6.             Class c=stu.getClass();   
  7.             Field field[]=c.getFields();   
  8.             for(int i=0;i<field.length;i++){   
  9.             System.out.println(field[i].getName());   
  10.             }   
  11.         }catch(Exception e){   
  12.             e.printStackTrace();   
  13.         }   
  14.     }   
  15.   
  16. }   
  17.   
  18. class Student{   
  19.     public int age;   
  20.     public int sno;   
  21.     public boolean gender;   
  22.     public String name;   
  23.     public Student(int age,int sno,boolean gender,String name){   
  24.         this.age=age;   
  25.         this.sno=sno;   
  26.         this.gender=gender;   
  27.         this.name=name;   
  28.     }   
  29. }   
  30. //运行结果 age,sno,gender,name  
import java.lang.reflect.Field;
public class FieldReflectTest {
	public static void main(String args []){
		try{
			Student stu=new Student(21,2003,true,"tom");
			Class c=stu.getClass();
			Field field[]=c.getFields();
			for(int i=0;i<field.length;i++){
			System.out.println(field[i].getName());
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}

class Student{
	public int age;
	public int sno;
	public boolean gender;
	public String name;
	public Student(int age,int sno,boolean gender,String name){
		this.age=age;
		this.sno=sno;
		this.gender=gender;
		this.name=name;
	}
}
//运行结果 age,sno,gender,name

从运行结果我们可以看出,我们可以利用对Student对象的反射,获得Student类的全部全局变量信息,注:只能获得修饰符为public 的全局变量,如果修饰符该为private将不能获得。 

3.Mehod类的简介,

  Method类的对象表示一个方法,主要用来携带方法的信息,它与Field类相似,不能通过构造器创建,而必须通过Class类的get方法来获得,主要可以使用的方法有:1.getName()获得方法名称,2.Class[] getParameterTypes()返回参数的序列, 3.Class getReturnType()返回方法返回值的类型。4.Object invoke(Object object,Object []args)此方法用来调用Method对象代表的方法,返回值是被调用方法的返回值,注:该方法无论方法返回什么值,都是做为Object对象返回。

Java代码 复制代码
  1. import java.lang.reflect.Method;   
  2. public class MethodReflect {   
  3.     public static void main(String args []){   
  4.         try{   
  5.             ForeMethod fore=new ForeMethod();   
  6.             Class cl=fore.getClass();   
  7.             Method method[]=cl.getMethods();   
  8.             for(int i=0;i<method.length;i++){   
  9.                 System.out.println("方法的返回值:"+method[1].getReturnType().getName());   
  10.                 System.out.println("方法的名称为:"+method[i].getName());   
  11.                 Class []cls=method[i].getParameterTypes();   
  12.                 for(int j=0;j<cls.length;j++){   
  13.                     System.out.print(method[i].getName()+"方法对应的参数为:"+cls[i].getName());   
  14.                 }   
  15.                 System.out.println();   
  16.             }   
  17.         }catch(Exception e){   
  18.             e.printStackTrace();   
  19.         }   
  20.     }   
  21.   
  22. }   
  23.  class ForeMethod{   
  24.     public void sayHello(String name){   
  25.         System.out.println("你好,"+name);   
  26.     }   
  27.     public String generateNum(int max,int min){   
  28.         return (Math.random()*(max-min))+"";   
  29.     }   
  30.  }  
import java.lang.reflect.Method;
public class MethodReflect {
	public static void main(String args []){
		try{
			ForeMethod fore=new ForeMethod();
			Class cl=fore.getClass();
			Method method[]=cl.getMethods();
			for(int i=0;i<method.length;i++){
				System.out.println("方法的返回值:"+method[1].getReturnType().getName());
				System.out.println("方法的名称为:"+method[i].getName());
				Class []cls=method[i].getParameterTypes();
				for(int j=0;j<cls.length;j++){
					System.out.print(method[i].getName()+"方法对应的参数为:"+cls[i].getName());
				}
				System.out.println();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
 class ForeMethod{
    public void sayHello(String name){
    	System.out.println("你好,"+name);
    }
    public String generateNum(int max,int min){
    	return (Math.random()*(max-min))+"";
    }
 }

 

通过这个列子,我们就可以简单的了解Method类在反射机制中的使用了

源自:http://www.iteye.com/topic/309508

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值