JAVA反射机制

正常的JAVA编程情况,我们只是对源码进行操作编程。而反射机制的存在,使得我们可以对JAVA字节码进行操作,就是我们编写的JAVA反射源码是对JAVA程序运行时的对象进行操作。

 

反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为(官网解释-http://docs.oracle.com/javase/tutorial/reflect/index.html:Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. )

用反射与不用反射的一个例子:

 

package com.ghost.t20140503;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

public class ReflectionTest {
	public static void main(String[] args) {
		// 一般做法
		MyClass myClass = new MyClass(10); 
		myClass.increase(5);
		System.out.println("正常编程方法得到-> " + myClass.getCount());
		try {
			// 获取构造方法
			Constructor<MyClass> constructor = MyClass.class.getConstructor(int.class);
			// 创建对象
			MyClass myClassReflect = constructor.newInstance(10);
			// 获取方法
			Method increaseMethod = MyClass.class.getMethod("increase", int.class);
			// 调用increase方法
			increaseMethod.invoke(myClassReflect, 5);
			
			Method getCountMethod = MyClass.class.getMethod("getCount");
			System.out.println("通过反射得到-> " + (int)getCountMethod.invoke(myClassReflect));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

class MyClass {
	private int count;
	public MyClass(int start) {
		count = start;
	}
	public void increase(int step) {
		count = count + step;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
}

 

一般来说,利用反射编程代码量大,性能也比原始的方法差,代码的可读性也差。那么反射存在的理由是什么呢?其实反射并不只是存在JAVA编程中。

在计算机科学领域,反射是指一类应用,它们能够自描述和自控制。也就是说,这类应用通过采用某种机制来实现对自己行为的描述(self-representation)和监测(examination),并能根据自身行为的状态和结果,调整或修改应用所描述行为的状态和相关的语义。

因此,反射可以让计算机更加智能,让程序可以了解自己,并根据实际情况对自己的结构进行改造。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值