java反射机制浅析和使用

Reflection--反射机制

一般而言,开发者社群说到动态语言,大致认同的一个定义是:“程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言”。从这个观点看,Perl,Python,Ruby是动态语言,C++,Java,C#不是动态语言。

尽管在这样的定义与分类下Java不是动态语言,它却有着一个非常突出的动态相关机制:Reflection。

这个字的意思是“反射、映象、倒影”,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。

换句话说,Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods。这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。

例如说我们可以通过反射机制来生成一个对象,并调用它的方法

反射机制就好像是设备的图纸库,通过图纸可以加工生成设备。

就好像说iphone咱们买不起,咱不知道它的构造,咱不知道它怎么使用,我们唯一知道的就是iphone这个高大光辉的名字(广大屌丝的悲哀)。

然而,惊天一声雷,幸运的是,反射机制出现了,为广大屌丝带来了新的希望。反射机制就像是一个设备图纸库,它的对外接口就是设备名,只要你有设备名就可以搜寻到该设备的对应的全部图纸。

oh 多么崭新的人生啊,你只需要轻轻搜索iphone,就会有相应的图纸出现在你的面前,有了图纸该做什么呢,我就不用解释了吧。

掌握核心科技,勇敢做自己,你,就是你......


机制实现的方式

/**
 *
 * @author zero
 * 1. Reflection has many forms, first, we need a Class object(Blueprint)

反射机制的实现由很多形式,但是,首先我们需要一个名称,不然怎么检索呢,通过名称我们获得Class 对象,也就是设计蓝图

 * 2. Use the Class object generate a new instance(real instance)

通过设计蓝图我们来制造一个真实对象,就是说根据设计蓝图制造一个真实的物件(当出现构造函数含有参数时,物件的设计师不想别人随便动用自己的设计,所以添加参数并且没有写在蓝图上,所以我们需要借助于constructor工具,并且要先打入内部,偷窃到构造方法如何实现,这样就可以创建出对象了)

 * 3. Use the instance to call the method

通过我们创建出来的对象来调用相关的方法


* for example:
 * we need a iphone : and there two types, one is knockoff(fade), another is real, the real iphone has its own ISBN number

我们想要一个iphone 这里有两种类型 一种是山寨的knockoff 另一个是真机, 真机有一个独一无二的ISBN编码,在制造它的时候必须给出启动码,这样就可以避免别人随便Copy

 * 1.we got the iphone's blueprint

同理  我们首先要获取到iphone的设计图纸

 * 2.use the blueprint we make the iphone , attention: if we need a real iphone, we should get the ISBN number and tools named Constructor

使用这个设计图纸 我们来制造一台iphone   注意这里我们要做真机的时候需要一个ISBN编码,并且需要一个叫做Cinstructor的工具来启动这个ISBN编码制造真机
 * 3.after that , we can use the phone to test the function 

在这之后,我们就可以始终这台我们创建的iphone来测试功能了


Tips:

The money is self willed:有钱任性

 */

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

/**
 * 
 * @author zero
 * 1. Reflection has many forms, first, we need a Class object(Blueprint)
 * 2. Use the Class object generate a new instance(real instance)
 * 3. Use the instance to call the method
 * for example:
 * we need a iphone : and there two types, one is knockoff(fade), another is real, the real iphone has its own ISBN number
 * 1.we got the iphone's blueprint
 * 2.use the blueprint we make the iphone , attention: if we need a real iphone, we should get the ISBN number and tools named Constructor
 * 3.after that , we can use the phone to test the function  
 */
public class Refection {
	public static void main(String[] args) throws Exception {
		Class iphoneBlueprint = Class.forName("KnockoffIphone");
		
		KnockoffIphone newIphone = (KnockoffIphone) iphoneBlueprint.newInstance();
		//generate a iphone directly .... opts:iphone's construction method with no arguments....
		newIphone.use();
		newIphone.destory();
		
System.out.println("");//A blank line
		Class iphoneBlueprint2 = Class.forName("RealIphone");
		Constructor constructor = iphoneBlueprint2.getDeclaredConstructor(new Class[]{int.class});
		
		RealIphone realIphone = (RealIphone)constructor.newInstance(new Object[]{89757});
		//generate a iphone with ISBN_number .... opts:iphone's construction method with arguments....
		realIphone.use();
		realIphone.destory();
	
System.out.println("");//A blank line

		//Call the appointed method that we know it's name and argument.....
		Method method = iphoneBlueprint.getMethod("use", null);
		method.invoke(newIphone, null);
		method = iphoneBlueprint.getMethod("destory", null);
		method.invoke(newIphone, null);
		
System.out.println("");

		//ergodic the method from the appointed instance
		Method[] methods = iphoneBlueprint.getDeclaredMethods();
		for(Method currentMethod : methods) {
			currentMethod.invoke(newIphone, null);
		}
	}
}

class KnockoffIphone {
	KnockoffIphone() {
		System.out.println("A new iphone produced.......");
	}
	
	public void use() {
		System.out.println("Use it to play..........");
	}
	
	public void destory() {
		System.out.println("Throw it away.The money is self willed.......");
	}
}


class RealIphone {
	int ISBN_Iphone;
	
	RealIphone(int ISBN_Iphone) {
		this.ISBN_Iphone = ISBN_Iphone;
		System.out.println(ISBN_Iphone + " iphone produced.......");
	}
	
	public void use() {
		System.out.println(ISBN_Iphone + " : play with it..........");
	}
	
	public void destory() {
		System.out.println(ISBN_Iphone +  " : Throw it away.The money is self willed.......");
	}
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值