java 反射 invoke使用

来源:互联网 发布:sql查询结果生成新表 编辑:程序博客网 时间:2024/05/20 16:12

学习了java反射,利用其功能写了一个小实例,将一个类中的属性值,赋值给具有相同属性值的另一个类的某个实例,并且得到该实例。

package com.basic.reflection;import java.lang.reflect.Method;public class TestInvoke {public static void main(String argv[]) {try {TestTBEE tbee = new TestTBEE();tbee.setAge(28);tbee.setName("lpn");tbee.setPhone("777");Class<?> clsTest = Class.forName("com.basic.reflection.Test");Class<?> clsTestTBEE = Class.forName("com.basic.reflection.TestTBEE");Object obj = clsTest.newInstance();Method ms[] = clsTest.getDeclaredMethods();for (Method m : ms) {if (m.getName().startsWith("set")) {String propertyName = m.getName().substring(3);String name = propertyName;                StringBuffer sb = new StringBuffer(propertyName);                  sb.replace(0, 1, (propertyName.charAt(0)+"").toLowerCase());                  propertyName = sb.toString();                                Method m_get = null;                try {                m_get = clsTestTBEE.getMethod("get"+name);                } catch (NoSuchMethodException e) {                continue;                }                if (m_get != null) {                m.invoke(obj, m_get.invoke(tbee));                }}}for (Method m : ms) {if (m.getName().startsWith("get")) {String propertyName = m.getName().substring(3);                  StringBuffer sb = new StringBuffer(propertyName);                  sb.replace(0, 1, (propertyName.charAt(0)+"").toLowerCase());                  propertyName = sb.toString();                System.out.println(m.invoke(obj));}}Test t = (Test)obj;System.out.println(t.getAge());} catch (Exception e) {e.printStackTrace();}}}class Test {private String name;private int age;private String sex;private String address;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 String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}}class TestTBEE {private String name;private int age;private String phone;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 String getPhone() {return phone;}public void setPhone(String phone) {this.phone = phone;}}
运行结果:

null
lpn
28
null

28

从这个结果可以看出,TestTBEE类的对象,将相同的属性值动态赋给了Test类的对象,并且可以得到该对象,主要是利用了Invoke方法。