黑马程序员———反射技术的高级应用

来源:互联网 发布:mac无法更新10.12.6 编辑:程序博客网 时间:2024/05/21 08:55

------<a href="http://www.itheima.com" target="blank">Java培训、Android培训、iOS培训、.Net培训</a>、期待与您交流------

一.反射在框架开发中的应用

1.1重写hashCode()和equals()方法,保证只要两个元素对象的属性值完全相同,equals()方法就返回true,并且两个元素对象的哈希值就相同(也即hashcode()方法返回值相同),也即不能成功向HashSet集合中添加属性值完全相同的两个元素对象,示例代码如下:

public class ReflectPoint {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;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic 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;}@Overridepublic String toString() {return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="+ str3 + ", x=" + x + ", y=" + y + "]";}}

public class ReflectDemo {public static void main(String[] args) {Collection<ReflectPoint> hs=new HashSet<ReflectPoint>();ReflectPoint rp1=new ReflectPoint(3, 3);ReflectPoint rp2=new ReflectPoint(5, 5);ReflectPoint rp3=new ReflectPoint(7, 7);ReflectPoint rp4=new ReflectPoint(3, 3);hs.add(rp1);hs.add(rp2);hs.add(rp3);hs.add(rp4);//添加rp4不成功,也即只添加了3个元素对象System.out.println(hs.size());//输出3rp4.y=5;hs.add(rp4);//修改rp4的属性值之后添加成功System.out.println(hs.size());//输出4}}

1.2我们在创建自定义类时可能会调用工具类,由于该工具类已经存在,所以可以直接调用,如果想要自定义类能够被框架调用,则必须把自定义类的类名添加到框架的配置文件中,框架通过读取配置文件中的类名,利用反射便可以创建出该类名对应的对象,示例代码如下:

public class ReflectPoint {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;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + x;result = prime * result + y;return result;}@Overridepublic 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;}@Overridepublic String toString() {return "ReflectPoint [str1=" + str1 + ", str2=" + str2 + ", str3="+ str3 + ", x=" + x + ", y=" + y + "]";}}

public class ReflectDemo {public static void main(String[] args) {try {FileInputStream fis=new FileInputStream("config.properties");Properties props=new Properties();//把与fis相关联的配置文件中的数据加载到Map集合props中props.load(fis);//关掉与fis相关联的系统资源fis.close();String className=props.getProperty("className");//利用反射根据类名创建出对应的对象Collection hs=(Collection)Class.forName(className).newInstance();//Collection<ReflectPoint> hs=new HashSet<ReflectPoint>();ReflectPoint rp1=new ReflectPoint(3, 3);ReflectPoint rp2=new ReflectPoint(5, 5);ReflectPoint rp3=new ReflectPoint(7, 7);ReflectPoint rp4=new ReflectPoint(3, 3);hs.add(rp1);hs.add(rp2);hs.add(rp3);hs.add(rp4);//添加rp4不成功,也即只添加了3个元素对象System.out.println(hs.size());//输出3rp4.y=5;hs.add(rp4);//修改rp4的属性值之后添加成功System.out.println(hs.size());//输出4} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

1.3使用类加载器加载配置文件,示例代码如下:

public class ReflectDemo {public static void main(String[] args) {try {//使用类加载器加载配置文件,此时配置文件和当前类ReflectDemo.java在相同目录下InputStream fis=ReflectDemo.class.getClassLoader().getResourceAsStream("com/heima/config.properties");Properties props=new Properties();//把与fis相关联的配置文件中的数据加载到Map集合props中props.load(fis);//关掉与fis相关联的系统资源fis.close();String className=props.getProperty("className");//利用反射根据类名创建出对应的对象Collection hs=(Collection)Class.forName(className).newInstance();//Collection<ReflectPoint> hs=new HashSet<ReflectPoint>();ReflectPoint rp1=new ReflectPoint(3, 3);ReflectPoint rp2=new ReflectPoint(5, 5);ReflectPoint rp3=new ReflectPoint(7, 7);ReflectPoint rp4=new ReflectPoint(3, 3);hs.add(rp1);hs.add(rp2);hs.add(rp3);hs.add(rp4);//添加rp4不成功,也即只添加了3个元素对象System.out.println(hs.size());//输出3rp4.y=5;hs.add(rp4);//修改rp4的属性值之后添加成功System.out.println(hs.size());//输出4} catch (FileNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InstantiationException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ClassNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}catch (ClassCastException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
二.反射在JavaBean中的应用
2.1对JavaBean的简单内省操作,示例代码如下:

public class JavaBean {private int x;private int y;public JavaBean(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;}}

public class JavaBeanDemo {public static void main(String[] args) {JavaBean jb=new JavaBean(3, 5);//定义属性名String propertyName="x";try {//获取属性描述器PropertyDescriptor pd=new PropertyDescriptor(propertyName, jb.getClass());//获取读取属性值的方法Method methodGetX=pd.getReadMethod();System.out.println(methodGetX.invoke(jb));//输出3//获取写入属性值的方法Method methodSetX=pd.getWriteMethod();methodSetX.invoke(jb, 7);System.out.println(methodGetX.invoke(jb));//输出7} catch (IntrospectionException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
2.1对JavaBean的复杂内省操作,示例代码如下:

public class JavaBeanDemo {public static void main(String[] args) {try {JavaBean jb=new JavaBean(5, 7);String propertyName="x";Object value=getProperty(jb, propertyName);System.out.println(value);//输出5} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IntrospectionException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public static Object getProperty(Object obj,String propertyName) throws IntrospectionException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{BeanInfo beanInfo=Introspector.getBeanInfo(obj.getClass());PropertyDescriptor[] pds=beanInfo.getPropertyDescriptors();Object RetVal=null;for (PropertyDescriptor pd : pds) {if(pd.getName().equals(propertyName)){Method methodGetX=pd.getReadMethod();RetVal=methodGetX.invoke(obj);break;}}return RetVal;}}



0 0
原创粉丝点击