黑马程序员 Java基础加强 反射

--------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Unity开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ------------------------------------------ 

反射

Class类(字节码文件)是反射的基石,反射的的基础条件是找到字节码文件。

反射就是把Java类中的各种成分映射成相应的Java类。

Data data=new Data( );

Class clazz1=Data.class;      Class clazz2=data.getClass( );       Class clazz3=Class.forName(data);

映射

Constructor类                         类中的构造函数

Method类                               类中的成员方法

Field类                                    类中的成员变量

获得方法时要用到类型,    调用获得的方法时要用到上面相同的类型的实例对象。

谁拥有数据谁就是干这时的专家   专家设计模式。

对接受数组参数的成员方法进行反射,数组于Object的关系及其反射类型

1具有相同维数和元素类型的数组,属于同一类型,即具有相同的class实例对象。

2代表数据的class实例对象的getSuperClass()方法,返回的父类为Object类对应的class。

3基本类型的一维数组可以被当作Oject类项使用,不能当作Object[]类型使用,非基本类型的一维数组,既可以当作Object类型使用,又可以

当作Object[]类型使用。

4Arrays.asList()方法处理int[]和String[]时的差异。

反射点

import java.util.Date;


public class ReflectPoint {
private Date birthday=new Date();
public Date getBirthday() {
return birthday;
}


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


private int x;
public int y;
public String str1="ball";
public String str2="basketball";
public String str3="itcast";


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

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;
}


@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 String toString()
{
return str1+":"+str2+":"+str3;
}
}




构造函数,成员方法,成员变量的反射 代码;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;


public class Reflect {


public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
String st="abc";
Class cls1=st.getClass();
Class cls2=String.class;
Class cls3=Class.forName("java.lang.String");
System.out.println(cls1==cls2);
System.out.println(cls1==cls3);

System.out.println(cls1.isPrimitive());
System.out.println(int.class.isPrimitive());
System.out.println(int.class==Integer.class);
System.out.println(int.class==Integer.TYPE);
System.out.println(int[].class.isPrimitive());
System.out.println(int[].class.isArray());

//new String(new StringBuffer("abc"));
 Constructor  constructor1=String.class.getConstructor(StringBuffer.class);
 String st2=(String)constructor1.newInstance(new StringBuffer("abc"));
 System.out.println(st2.charAt(2));
 
 ReflectPoint pt1=new ReflectPoint(3, 5);
 Field fieldY=pt1.getClass().getField("y");
 //fieldY的值是多少?是,错!fieldY不是对象身上的变量,而是类上,要用它去取某个对象上对应的值。
 System.out.println(fieldY.get(pt1));
 
 Field fieldX=pt1.getClass().getDeclaredField("x");
 fieldX.setAccessible(true);//暴力反射
 System.out.println(fieldX.get(pt1));
 
 changeStringValue(pt1);
 System.out.println(pt1);
 
 //st.CharAt(1);
 Method methodCharAt=st.getClass().getMethod("charAt", int.class);
 System.out.println(methodCharAt.invoke(st,1));
 
 //TestArguments.main(new String[]{"111","222","333"});
 String startingClassName=args[0];
 Method mainMethod=Class.forName(startingClassName).getMethod("main",String[].class);
 //mainMethod.invoke(null,new Object[]{ new String[]{"111","222","333"}});//null静态调用
 mainMethod.invoke(null, (Object) new String[]{"111","222","333"});
 
 int[] a1=new int[]{1,2,3};
 int[] a2=new int[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()==a3.getClass());false
// System.out.println(a1.getClass()== a4.getClass());false
 System.out.println(a1);
 System.out.println(a1.getClass().getSuperclass().getName());
 System.out.println(a4.getClass().getSuperclass().getName());
 
 Object aobj1=a1;
 Object aobj2=a4;
 //Object[] aobj3=a1;false
 Object[] aobj4=a3;
 Object[] aobj5=a4;
 
 System.out.println(a1);
 System.out.println(a4);
 System.out.println(Arrays.asList(a1));
 System.out.println(Arrays.asList(a4));
 
 printObject(a4);
 printObject("xyz");
}




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));
}
}else{
System.out.println(obj);
}
}








public static void  changeStringValue(Object obj)throws Exception
{
Field[] fields=obj.getClass().getFields();
for(Field field: fields)
{
//if(field.getType().equals(String.class))
if(field.getType()==String.class)
{
String oldValue=(String)field.get(obj);
String newValue=oldValue.replace('b','a');
field.set(obj, newValue);
}
}
}


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

}

内省



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;


public class IntroSpectorTest {


public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ReflectPoint pt1=new ReflectPoint(3,5);
String propertyName="x";

PropertyDescriptor pd=new PropertyDescriptor(propertyName, pt1.getClass());
Method methodGetX=pd.getReadMethod();
Object retVal=methodGetX.invoke(pt1);
System.out.println(retVal);

Method methodSetX=pd.getWriteMethod();
methodSetX.invoke(pt1, 7);


System.out.println(BeanUtils.getProperty(pt1, "x").getClass().getName());
BeanUtils.setProperty(pt1, "x", "18");
System.out.println(pt1.getX());

BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));
/*java7 的新特性   不行啊。
Map map={name:"zhansan",age:18};
BeanUtils.setProperty(map, name, "liming");
*/

System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());
PropertyUtils.setProperty(pt1, "x", 18);

}
public static Object getProperty(Object pt1,String propertyName) throws IntrospectionException,
IllegalAccessException, IllegalArgumentException, InvocationTargetException
{
BeanInfo beanInfo=Introspector.getBeanInfo(pt1.getClass());
PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();
Object retVal=null;
for(PropertyDescriptor pd:pds)
{
if(pd.getName().equals(propertyName))
{
Method methodGetX=pd.getReadMethod();
retVal=methodGetX.invoke(pt1);
break;
}
}
return retVal;
}



}




import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.*;


public class ReflectTest2 {


public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
//InputStream ips=new FileInputStream("config.properties");

//InputStream ips=ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
InputStream ips=ReflectTest2.class.getResourceAsStream("resource/config.properties");
Properties props=new Properties();
props.load(ips);
ips.close();

String className=props.getProperty("className");
Collection collection=(Collection)Class.forName(className).newInstance();
//Collection collection=new HashSet();
ReflectPoint pt1=new ReflectPoint(3,3);
ReflectPoint pt2=new ReflectPoint(5,5);
ReflectPoint pt3=new ReflectPoint(3,3);
collection.add(pt1);
collection.add(pt2);
collection.add(pt3);
collection.add(pt1);
//pt1.y=7;//存储后再修改参与哈希值运算的变量,无法删除啦,内存泄漏。
//collection.remove(pt1);
System.out.println(collection.size());
}


}

--------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Unity开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ------------------------------------------ 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值