Java加强--反射


 

JAVA 反射是把Java类中的各种成分映射成相应的java类。表示java类的Class类显然要提供一系列的方法来获得其中的变量,方法,构造方法,修饰符,包等信息,写信息是用相应类的实例对应那个类来表示,它们是Field Method,Contructor,Package等等。一个类中的每一个成员变量都可以用相应的的反射API类的一个实例对象来表示,通过来调用Class类的方法可以得到这些实例对像。
    
反射的作用:Java反射机制主要提供了以下功能:在运行时判定任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判定任意一个类所具有的成员变量和方法;在运行时调用任意一个对象的方法;生成动态代理。
 
反射的基石->Class类
 * Java程序中的各个Java类属于同一种事物,描述这类事物的Java类名就是Class类
 * 如何得到各个字节码对应的实例对象
 * 1》类名.class 如:System.class
 * 2》对象.getclass 如:new Date.getclass
 * 3》Class.forName("类名") 如:Class.forName("java.util.Date");
 *
 * 数组的类型的实例对象   Class.isArray()
 *
 * 九个预定义的Class对象  基本的 Java 类型(boolean、byte、char、short、int、long、float 和 double)
 * 和关键字 void 也表示为 Class 对象。
 *
 * 只要元程序中出现的类型都有各自的Class实例对象 如:int[],void....
 *
 * 反射就是将Java类中的各种成分映射成相应的类;
下面代码中包括:构造方法的发射,成员变量的反射,成员方法的反射 

<span style="font-size:18px;">构造方法的反射:

public class ConstructorDemo {

	public static void main(String[] args) throws Exception{
		String str = "abc";
		/*
		用反射的方法实现 new String(new StringBuffer("abc"));
		Constructor构造方法的反射
	*/ 
		//获去一个StringBufffer的构造方法,创建方法要有类型
		Constructor constructor = String.class.getConstructor(StringBuffer.class);
		//创建一个StringBufffer的对象“abc”,调用方法时要有对象
		String str1 = (String)constructor.newInstance(new StringBuffer("abc"));
		System.out.println(str);
	}
}

成员变量的映射:
public class ReflectPoint {
	public int x;
	private int y;
	public ReflectPoint(int x, int y){
		super();
		this.x = x;
		this.y = y;	
	}
}
public class ReflectText {
    
	public static void main(String[] args) throws Exception {

              //成员变量的反射  分别获取x 和 y的值
	ReflectPoint pt = new ReflectPoint(3,5);
	//fieldx不是对象身上的变量,而是类上,它去取某个对象上对应的值
	Field fieldx = pt.getClass().getField("x");
	System.out.println(fieldx.get(pt));
	
	Field fieldy = pt.getClass().getDeclaredField("y");//无论是私有还是共有都能取到
	fieldy.setAccessible(true);//暴力反射
	System.out.println(fieldy.get(pt));
}

成员方法的映射:
public class ReflectText {
    
	public static void main(String[] args) throws Exception {

		//成员方法的反射
	String str = "abc";
	//用反射方法求str.charAt(1);  
	Method methodCharAt = String.class.getMethod("charAt",int.class);
	System.out.println(methodCharAt.invoke(str,1));
	
}
对接收数组参数的成员方法进行反射:

public class Text {
	public static void main(String[] args) {
		for(String arg : args){
			System.out.println(arg);
		}	
	}
}

public class ReflectText {
    
	public static void main(String[] args) throws Exception {
/*	
	根据用户提供的类名调用该类的main方法,常用方式调用
	Text.main(new String[]{"aa","bb","dd"});
          用反射方法实现上述结果
*/	
	String startingClassName = args[0];
	Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
	mainMethod.invoke(null, new Object[]{new String[]{"aa","bb","dd"}});
//	mainMethod.invoke(null,(Object)new String[]{"aa","bb","dd"});等同于上一行代码
 

}
</span>
<span style="font-size:18px;"></span> 
<span style="font-size:18px;">数组的反射
import java.lang.reflect.Array;
import java.util.Arrays;
public class ArrayDemo {

	public static void main(String[] args) {
		int[] a = new int[]{2,4,5};
		int[] b = new int[5];
		int[][] c = new int[3][3];
		String[] d = new String[]{"a","b","c"};
		System.out.println(a.getClass() == b.getClass());
		System.out.println(a.getClass().getSuperclass().getName());
	
		Object obj1 = a;
		Object obj2 = d;
		Object[] obj3 = c;
		Object[] obj4 = d;
		System.out.println(Arrays.asList(a));
		System.out.println(Arrays.asList(d));
	
		printObject(a);
	}

	private static void printObject(Object obj) {
		Class clazz = obj.getClass();
		if(clazz.isArray()){
			int len = Array.getLength(obj);
			for(int i = 0; i < len; i++){
				System.out.println(Array.get(obj, i));
				
			}
		}
		
	}
}
</span>

综合举例:反射的应用,实现框架的功能;


config.properties  文件
className=java.util.ArrayList
public class ReflectPoint {

	private int x;
	public int y;
	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
}
public class Demo {
	
	public static void main(String[] args) throws Exception{
		//将属性列表添加到输入流中
		InputStream ips = new FileInputStream("config.properties");
		Properties prop = new Properties();
		prop.load(ips);//从输入流中读取属性列表
		ips.close();
		String className = prop.getProperty("className");//用指定的键获相应的属性
		//创建Class对象表示的类的一个实例对象
		Collection collection = (Collection) Class.forName(className).newInstance();
				
			ReflectPoint pt = new ReflectPoint(3,3);
			ReflectPoint pt1 = new ReflectPoint(5,5);
			ReflectPoint pt2 = new ReflectPoint(2,3);
			
			collection.add(pt);
			collection.add(pt1);
			collection.add(pt2);
			collection.add(pt1);
			
			System.out.println(collection.size());
	}
}


 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值