Java 反射 大演练

反射:就是将一个类的各个成员映射成相应的类

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;

public class ReflectTest {
	public static void main(String[] args) throws Exception{

		Class clazz=void.class;
		String str1="abc";
		
		Class cls=str1.getClass();
		Class cls1=String.class;
		Class cls2=Class.forName("java.lang.String");
		
		System.out.println(cls==cls1);
		System.out.println(cls1==cls2);
		
		//字节码是否是 基本数据类型
		System.out.println(cls.getName());  //获取 class的 名字
		System.out.println(cls.isPrimitive());
		System.out.println(int.class.isPrimitive());
		System.out.println(int.class==Integer.class);

		//获取Integer的基本类型
		System.out.println(Integer.TYPE==int.class);  
		//判断数组是不是基本数据类型
		System.out.println(int[].class.isPrimitive());
		//判断class 是不是 数组类型
		System.out.println(int[].class.isArray());
		
		//反射调用构造函数
		getConstructor();
		
		//使用 反射创建对象
		newInstance();
		
		//反射获取 字段
		reflectGetField();
		
		//反射 获取方法 并调用方法
		reflectInvoke(str1);
		
		//调用main方法
		TestArgusments.main(new String[]{"sdf","sdf","sdf"});
		
		//使用反射调用main方法
		String  className=args[0];
		Method mainMethod=Class.forName(className).getMethod("main", String[].class);
		mainMethod.invoke(null, (Object)new String[]{"aaa","bbb","ccc"});  //由于 jdk1.5  要兼容 1.4  所以就采用jdk1.4 的方式(1.4进行拆包)
		
		//数组的反射
		reflectArray();
	}
	
	//获取 Class 的构造方法
	public static void getConstructor() throws Exception{
		Constructor [] constructors=String.class.getConstructors();
		System.out.println("length:"+constructors.length+"\ndetail:"+Arrays.toString(constructors));
		
		//使用反射 调用构造方法 实现 创建对象 
		//new String(new StringBuffer("abc"));
		Constructor constructor=String.class.getConstructor(int[].class,int.class,int.class);
		constructor=String.class.getConstructor(StringBuffer.class);
		String str2=(String) constructor.newInstance(new StringBuffer("abc"));
		System.out.println(str2.charAt(2));
	}
	//Class 的 newInstance 省略了 构造函数的 newInstance 步骤
	public static void newInstance() throws Exception{
		String str1=(String)Class.forName("java.lang.String").newInstance();
		System.out.println(str1);
	}
	
	
	public static void reflectGetField() throws Exception{
		Class clazz=Class.forName("com.enhance.reflect.ReflectPoint");
		Constructor<ReflectPoint> cons=clazz.getConstructor(int.class,int.class);
		ReflectPoint rfp=rfp=(ReflectPoint)clazz.newInstance();  //声明的类必须要有 无参构造方法 
		System.out.println(rfp.y);
		rfp=cons.newInstance(3,5);
		System.out.println(rfp.y);
		
		Field [] fields=clazz.getFields();  //只能获取 非私有字段 
		System.out.println(Arrays.toString(fields));  //只能 处理 私有的字段  其他都能获取
		
		fields=clazz.getDeclaredFields();  //获取所有 声明的字段
		System.out.println(Arrays.toString(fields));  //只能 处理 私有的字段  其他都能获取
		
		Field fy=rfp.getClass().getField("y");
		System.out.println(fy.get(rfp));  //从某个对象中获取  字段的值
		System.out.println(Modifier.toString(fy.getModifiers()));  //获取修饰符
		System.out.println(fy.getType());  //获取字段类型
		
		//获取私有字段
		Field fx=rfp.getClass().getDeclaredField("x");  //
		fx.setAccessible(true);// 暴力访问 
		System.out.println(fx.get(rfp));
		
		reflectReplace(rfp);
		System.out.println(rfp);
		
		
	}
	
	public static void reflectReplace(Object obj) throws Exception{
		
		Field[] fields=obj.getClass().getDeclaredFields();
		for (Field field : fields) {
			//字节码 用 ==进行比较 
			if(field.getType()==String.class){  
				if(field.getModifiers()==Modifier.PRIVATE){
					field.setAccessible(true);
					System.out.println("accessible");
				}
				String oldVal=(String)field.get(obj);
				String newVal=oldVal.replace('b', 'a');
				field.set(obj, newVal);
			}
			
		}
	}
	
	public static void reflectInvoke(String str) throws Exception{
		Method methodCharAt=str.getClass().getMethod("charAt", int.class);
		System.out.println(methodCharAt.invoke(str, 1));
		
		methodCharAt.invoke(str, 1);  //改方法 是静态 方法 ,不需要对象 
	}
	
	
	public static void reflectArray(){
		int[] a1=new int[]{1,2,3};
		int[] a2=new int[]{1,2,3,4};
		int[][] a3=new int[2][3];
		
		String [] a4=new String[]{"a","b","c"};
		
		System.out.println(a1.getClass()==a2.getClass());
		//System.out.println(a1.getClass()==a4.getClass());
		//System.out.println(a1.getClass()==a3.getClass());
		System.out.println(a1.getClass().getName());
		System.out.println(a1.getClass().getSuperclass().getName());
		System.out.println(a3.getClass().getName());
		System.out.println(a3.getClass().getSuperclass().getName());
		System.out.println(a4.getClass().getSuperclass().getName());
		System.out.println(a4.getClass().getName());
		
		Object aobj=a1;
		Object bobj=a3;
	//	Object[] aobj1=a1;
		Object obj5=a4;
		System.out.println("=================");
		System.out.println(Arrays.asList(a1));
		System.out.println(Arrays.asList(a4));
		
		//使用反射开始
		printObj("xyz");
		printObj(a4);
		HashSetAndArryList();
	}
	
	//hashCode  
	public static void HashSetAndArryList(){
		Collection collections=new ArrayList();
		ReflectPoint pt1=new ReflectPoint(2,2);
		ReflectPoint pt2=new ReflectPoint(5,5);
		ReflectPoint pt3=new ReflectPoint(2,2);
		
		collections.add(pt1);
		collections.add(pt2);
		collections.add(pt3);
		collections.add(pt1);
		System.out.println(collections.size());
		
		collections=new HashSet();
		collections.add(pt1);
		collections.add(pt2);
		collections.add(pt3);
		collections.add(pt1);
		System.out.println(collections.size());
		pt1.y=3;
		collections.remove(pt1);  //没有删除掉. 会内存溢出了
		System.out.println(collections.size());
		
	}
	
	
	public static void printObj(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));
			}
		}else{
			System.out.println(obj);
		}
		
		
	}
}

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

//使用反射操作 javabean

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

/**
 * 使用内省的方式来操作javabean
 * 
 * 使用BeanUtils
 * @author Bin
 */
public class IntroSpectorTest {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws Exception{
		System.runFinalizersOnExit(true);
		
		
		ReflectPoint pt=new ReflectPoint(3,7);
		String propertyName="x";
		//"x"--->"X"---->getX---->MethodgetX
		
		Object retVal = getProperty(pt, propertyName);
		System.out.println(retVal);
		//BeanUtils
		System.out.println(BeanUtils.getProperty(pt, "x"));

		//BeanUtils.接受和返回的都是String类型
		System.out.println(BeanUtils.getProperty(pt, "x").getClass().getName());
		
		Object value=7;
		Object retVal1 = setProperty(pt, propertyName, value);
		BeanUtils.setProperty(pt, "x", "9");
		
		System.out.println(retVal1);
		System.out.println(pt.getX());
		
		
		//BeanUtils 给复合属性复制 
		BeanUtils.setProperty(pt, "birthday.time", "1111");
		System.out.println(BeanUtils.getProperty(pt, "birthday"));
		
		//java 7 的新特性 给Map设置
		/*Map map={name:"zxx",age:18};
		BeanUtils.setProperty(map, "name", "lhm");*/
		
		PropertyUtils.setProperty(pt, "x", 15);
		System.out.println(PropertyUtils.getProperty(pt, "x"));
	}

	@Deprecated
	private static Object setProperty(Object obj, String propertyName,
			Object value) throws IntrospectionException,
			IllegalAccessException, InvocationTargetException {
		PropertyDescriptor pd2=new PropertyDescriptor(propertyName, obj.getClass());
		Method methodSet=pd2.getWriteMethod();
		Object retVal1=methodSet.invoke(obj, value);
		return retVal1;
	}

	
	private static Object getProperty(Object obj, String propertyName)
			throws IntrospectionException, IllegalAccessException,
			InvocationTargetException {
		//优秀的代码
		PropertyDescriptor pd1=new PropertyDescriptor(propertyName, obj.getClass());
		Method methodGet=pd1.getReadMethod();
		Object retVal=methodGet.invoke(obj);
		
		//不太好的代码
		BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());
		PropertyDescriptor [] pds=beanInfo.getPropertyDescriptors();
		for (PropertyDescriptor pd : pds) {
			if(propertyName.equals(pd.getName())){
				retVal=pd.getReadMethod().invoke(obj);
				break;
			}
		}
		return retVal;
	}
}






public class ReflectPoint {
	
	private Date birthday=new Date();
	private int x;
	public int y;
	public boolean flag;
	private String CPU;
	private String bRide;
	

	private String str = "ball";
	public String str1 = "basketball";
	String str2 = "football";
	protected String str3 = "Vectball";

	public ReflectPoint() {
		super();
		// TODO Auto-generated constructor stub
	}

	public ReflectPoint(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}

	@Override
	public String toString() {
		// TODO Auto-generated method stub
		return str + ":" + str1 + ":" + str2;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + x;
		result = prime * result + y;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		ReflectPoint other = (ReflectPoint) obj;
		if (x != other.x)
			return false;
		if (y != other.y)
			return false;
		return true;
	}

	public boolean isFlag() {
		return flag;
	}

	public void setFlag(boolean flag) {
		this.flag = flag;
	}

	public String getCPU() {
		return CPU;
	}

	public void setCPU(String cPU) {
		CPU = cPU;
	}

	public int getX() {
		return x;
	}

	public void setX(int x) {
		this.x = x;
	}

	public int getY() {
		return y;
	}

	public void setY(int y) {
		this.y = y;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	
}

public class LoadProperties {
	public static void main(String[] args){
		try {
			//InputStream ips=new FileInputStream("src/com/enhance/reflect/config.properties");//src/com/enhance/reflect/config.properties
			
//			InputStream ips=LoadProperties.class.getClassLoader().getResourceAsStream("com/enhance/reflect/config.properties");
			//InputStream ips=LoadProperties.class.getResourceAsStream("config.properties");
			InputStream ips=LoadProperties.class.getResourceAsStream("resource/config.properties");
			
			Properties props=new Properties();
			props.load(ips);
			ips.close();
			String classname=props.getProperty("classname");
			Collection collections=(Collection)Class.forName(classname).newInstance();
			
			ReflectPoint pt1=new ReflectPoint(3,3);
			ReflectPoint pt2=new ReflectPoint(4,3);
			ReflectPoint pt3=new ReflectPoint(3,3);
			collections.add(pt1);
			collections.add(pt2);
			collections.add(pt3);
			
			System.out.println(collections.size());
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
}





package com.enhance.Generic;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.Vector;

import org.junit.runners.Parameterized;

/**
 *使用反射 获取 某个 类中 方法 的参数类型,包括 泛型类型
 */
public class GenericTest {
	public static void main(String[] args) throws Exception{


Method applyMethod=GenericTest.class.getMethod("applyVector", Vector.class);
		Type[] types =applyMethod.getGenericParameterTypes();
		ParameterizedType pType=(ParameterizedType)types[0];
		System.out.println(pType.getRawType());
		System.out.println(pType.getActualTypeArguments()[0]);
		
		Method applyMethod1=GenericTest.class.getMethod("applyString", String.class);
		Class[] cls =applyMethod1.getParameterTypes();
		System.out.println(cls[0]);
		
		System.out.println("=============");
		Method[] mms=GenericTest.class.getMethods();
		for (Method method : mms) {
			Class[] cls1 =method.getParameterTypes();
			System.out.println(method.getName()+":"+Arrays.toString(cls1));
		}

}


	//自动类型转换   泛型 可以根据返回值类型来定义
	public static <T> T autoConvert(Object obj){
		return (T)obj;
	}
	
	//使用反射获取 applyVector方法中  参数的类型 ,包括  Vector 中 T 泛型类型 
	public static void applyVector(Vector<Date> v1){
		
	}
	
	public static void applyString(String v1){
		
	}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值