Java反射机制笔记-反射机制

来源:互联网 发布:二战苏联伙食知乎 编辑:程序博客网 时间:2024/04/28 05:06
反射主要是指程序可以访问、检测和修改它本身状态或行为的一种能力。Java反射机制是在进行状态中,对于任意一个类,都能够知道这个类的所有属性和方法,对于任意一个对象,都能够调用它的任意一个方法。本实例介绍反射类的方法以及如何获得和调用其他类的属性、构造方法和方法信息。
技术要点:
运用反射的技术要点如下:
反射机制提供以下功能:在运行时判断任意一个对象所属的类;在运行时构造任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法。
package core;import java.lang.reflect.Array;import java.lang.reflect.Field;import java.lang.reflect.Method;class Customer {// 用户类private Long id; // 用户编号private String name;// 用户名称private int age; // 年龄public Customer() {}// 默认构造方法public Customer(String name, int age) {// 带参构造方法this.name = name;this.age = age;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public void showInfo(String salary){System.out.println("薪水: "+ salary+" RMB");}}public class TextReflect {public Object getProperty(Object obj) throws Exception {// 取得参数对象中的属性Class<?> classType = obj.getClass();// 获取对象的类型System.out.println("class:" + classType.getName());// 调用的这两个方法要仔细查阅资料 Object objectCopy=classType.getConstructor(new Class[]{}).newInstance(new Object[]{});//通过默认构造方法创建一新对象Field fields[] = classType.getDeclaredFields();//获取对象的所有属性for (int i = 0; i < fields.length; i++) {//循环输出该对象的每一个属性Field field=fields[i];String fieldName=field.getName();String firstLetter=fieldName.substring(0,1).toUpperCase();//首先把每个属性列的首字母变为大写//get方法String getMethodName="get"+firstLetter+fieldName.substring(1);//获得属性对应的getXxx()方法get+大写首字母+首字母之后的字符串拼接起来 Method getMethod=classType.getMethod(getMethodName, new Class[] {});//获取和属性对应的getXxx()方法Object value=getMethod.invoke(obj, new Object[] {});//调用原对象的getXxx()方法得到该属性列所对应的值System.out.println(fieldName+":"+ value);//set方法String setMethodName="set"+firstLetter+fieldName.substring(1);//获得属性对应的setXxx()方法set+大写首字母+首字母之后的字符串拼接起来 Method setMethod=classType.getMethod(setMethodName, new Class[] {field.getType()});//获取和属性对应的setXxx()方法setMethod.invoke(objectCopy, new Object[] {value});//调用拷贝对象的setXxx()方法//System.out.println(""+objectCopy.toString());}return objectCopy;}public Object getPrivatePropertyValue(Object obj,String propertyName) throws Exception{//获取参数对象的属性值Class cls=obj.getClass();//获取对象的类型Field field=cls.getDeclaredField(propertyName);//获取对象的指定属性field.setAccessible(true);//属性允许访问Object retvalue=field.get(obj);//获取obj对象的属性field所对应的值return retvalue;}public Object invokeMethod(Object owner,String methodName,Object[] args) throws Exception{//执行某对象的方法Class<?> cls=owner.getClass();//获取对象的类型Class[] argclass=new Class[args.length];//对象参数for (int i = 0; i < argclass.length; i++) {argclass[i]=args[i].getClass();  //获取参数的类型,即形参}Method method=cls.getMethod(methodName, argclass);//获取对象方法 argclass为形参return method.invoke(owner, args);//args为实参}public void invokeMethod() throws Exception{//调用类的方法Class<?> classType=TextReflect.class;Object invokeTester=classType.newInstance();Method addMethod=classType.getMethod("add", new Class[]{int.class,int.class});//调用TextReflect对象的add()方法,形参Object result=addMethod.invoke(invokeTester, new Object[]{new Integer(100),new Integer(200)});//获取方法结果,实参System.out.println("result : "+result);Method echoMethod=classType.getMethod("echo", new Class[]{String.class});Object echo=echoMethod.invoke(invokeTester, "Hello");System.out.println("echo : "+echo);}public int add(int num1,int num2){return num1+num2;}public String echo(String info){return info;}public static void main(String[] args) throws Exception {TextReflect tr = new TextReflect();// 实例化对象Customer customer = new Customer("lingda", 20); // 对象初始化customer.setId(new Long(1));System.out.println("1.取得参数对象中的全部属性");Customer cu = (Customer) tr.getProperty(customer);System.out.println("用户信息:编号--"+cu.getId()+",名称--"+cu.getName()+",年龄--"+cu.getAge());System.out.println("2.获取参数对象的属性值:");String userName=(String) tr.getPrivatePropertyValue(customer, "name");System.out.println("用户名称:"+ userName);System.out.println("3.执行某对象的方法");tr.invokeMethod(customer, "showInfo", new Object[]{"2000"});System.out.println("4.调用本类的方法");tr.invokeMethod();}}

源程序解读:
(1)getProperty()方法首先获得对象的类型及名称,其中"?"表示可获得任意类型的对象。再通过默认构造器创建一个新的对象。通过getDeclaredFields()方法获得传入对象的所有属性,循环遍历属性中,可以根据属性的名字的名字获得相应属性的getXxx和setXxx方法。最后调用对象中的getXxx方法,接收该方法的返回值。将获得的返回值传入setXxx方法中。
(2)getPrivatePropertyValue()方法根据传入的对象获得对象类型,根据传入的属性获得对象的指定属性。当访问的属性的访问修饰符为private时,需要设置setAccessible的值为true。这样便获得属性对应的值。
(3)在含有参数的invokeMethod()方法中,根据传入的对象、对象方法以及对象方法需要的参数获得相应的对象类型、带参数的方法。根据invoke()方法获得方法执行后返回的结果。
(4)在没有参数的invokeMethod()方法中创建TextReflect对象类型。根据getMethod()方法调用此对象的add()并设置方法的参数是整型,调用此对象的echo()方法并设置方法的参数是对象。根据invoke()方法获得方法返回的结果。



原创粉丝点击