Java 反射机制浅谈

1、reflect的定义

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制.

2、reflect的抽象分析,具体如下:

1)、对类的分析,抽象为class对象

2)、对构造方法的分析,抽象为Constructor类的对象

3)、对成员变量的分析,抽象为Field类的对象

4)、对方法的分析,抽象为Method类的对象

3、reflect机制简单实例

1)、定义Computer.java类

package cn.java.example;

public class Computer {
	
	private String cpuType;
	private int memory;
	private String display;
	
	public String getCpuType() {
		return cpuType;
		
	}
	public void setCpuType(String cpuType) {
		this.cpuType = cpuType;
	}
	public int getMemory() {
		return memory;
	}
	public void setMemory(int memory) {
		this.memory = memory;
	}
	public String getDisplay() {
		return display;
	}
	public void setDisplay(String display) {
		this.display = display;
	}
	
	
	

}
2)、反射测试类

package cn.java.example;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class TestReflect {

	public static void main(String[] args) {
		
		Class<Computer> clazz=Computer.class;
		
		try {
			
			//获得Computer类的cpuType属性对象
			Field field=clazz.getDeclaredField("cpuType");
			System.out.println(field.getName());
			System.out.println(field.getType());
			System.out.println(field.getModifiers());
			
			
			System.out.println("/********************/");
			
			Field[] fieldAll=clazz.getDeclaredFields();
			//遍历所有的属性
			for (Field field2 : fieldAll) {
				System.out.println(field2.getName());
				System.out.println(field2.getType());
				System.out.println(field2.getModifiers());
				
			}//for
			
			System.out.println("/********************/");
			
			//为thinkPad没有设置的memory赋值
			Computer thinkPad=new Computer();
			Field memory=clazz.getDeclaredField("memory");
			memory.setAccessible(true);//取消对memory属性的修饰符的检查访问,以便为memory属性赋值
			memory.setInt(thinkPad, 500);
			memory.setAccessible(false);回复对memory属性的修饰符的检查访问
			System.out.println("My thinkPad memory is "+thinkPad.getMemory()+"G");
			
			System.out.println("/********************/");
			
			//method获取的方法
			Method method=clazz.getDeclaredMethod("getCpuType");
			System.out.println(method.getName());
			System.out.println(method.getModifiers());
			
			
			
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}catch (NoSuchMethodException e) {
			e.printStackTrace();
		}

	}

}






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值