Java中的反射和内省简单实例

来源:互联网 发布:c 数组赋值 编辑:程序博客网 时间:2024/06/04 18:40


1.反射和内省   

      反射式在运行状态把Java类中的各种成分映射成相应的Java类,可以动态的获取所有的属性以及动态调用任意一个方法,强调的是运行状态。

      内省机制是通过反射来实现的,BeanInfo用来暴露一个bean的属性、方法和事件,以后我们就可以操纵该JavaBean的属性。


2.反射和内省的图



一个简单的实例:

Person.java

public class Person{private Integer id;private String name;public Person(){super();}public Person(Integer id, String name){super();this.id = id;this.name = name;}public Integer getId(){return id;}public void setId(Integer id){this.id = id;}public String getName(){return name;}public void setName(String name){this.name = name;}@Overridepublic String toString(){return "Person [id=" + id + ", name=" + name + "]";}}

测试类:

public class IntrospectorAndReflect{/*** @throws Exception  * @Description: 使用反射设置值和调用方法 */@Testpublic void test1() throws Exception{Class<?> clazz = Class.forName("com.beanutil.px.Person");Object obj = clazz.newInstance();//-----------set value-----------Field id = clazz.getDeclaredField("id");id.setAccessible(true);id.set(obj, 1001);Field name = clazz.getDeclaredField("name");name.setAccessible(true);name.set(obj, "你好");//------------get value----------Method[] methods = clazz.getMethods();for(Method m : methods){if(m.getName().startsWith("get")){Object v = m.invoke(obj, null);System.out.println(v);}}}/*** @throws Exception  * @Title: test2* @Description: 使用内省的方式修改属性和调用方法 */@Testpublic void test2() throws Exception{Person p = new Person();BeanInfo bi = Introspector.getBeanInfo(Person.class);PropertyDescriptor[] pds = bi.getPropertyDescriptors();for(PropertyDescriptor pd : pds){System.out.println(pd.getName());}System.out.println("===================");//-------------set value----------------PropertyDescriptor id = new PropertyDescriptor("id", Person.class);Method wid = id.getWriteMethod();wid.invoke(p, 1002);PropertyDescriptor name = new PropertyDescriptor("name", Person.class);Method wname = name.getWriteMethod();wname.invoke(p, "hello");//--------------get value-----------------------Method gid = id.getReadMethod();System.out.println(gid.invoke(p, null));Method gname = name.getReadMethod();System.out.println(gname.invoke(p, null));}/** * * @throws Exception  * @throws IllegalAccessException  * @Title: test3* @Description: 使用Apache-common beanutil框架内部采用内省的方式进行设置和获取 */@Testpublic void test3() throws Exception{Person p = new Person();BeanUtils.setProperty(p, "id", 1003);BeanUtils.setProperty(p, "name", "world");System.out.println(p);String name = BeanUtils.getProperty(p, "name");System.out.println("name: "+name);}}

PS:使用beanutil需要添加logging的jar包。


0 0