I、getType() 和 getGenericType()的区别 :
b.如果属性是一个泛型,从getType()只能得到这个属性的接口类型。但从getGenericType()还能得到这个泛型的参数类型。
public class ReflectDemo { public ReflectDemo() { // TODO Auto-generated constructor stub } public static void main(String[] args) { // 使用反射机制进行处理 try { //================获取反射对象============================================= System.out.println("********************获取反射对象********************"); // 获取消息处理方法 Class clazz = AddressReflect.class; // forName中的参数一定是完整的类名(包名+类名),效果与AddressReflect.class一样 // Class clazz = Class.forName("com.swh.xml.entity.AddressReflect"); System.out.println("============clazz=" + clazz); //================获取构造方法============================================= System.out.println("********************获取构造方法 并执行********************"); Constructor con = clazz .getDeclaredConstructor(new Class[] { String.class ,Integer.class}); con.setAccessible(true); // 设置可访问的权限 Object obj = con.newInstance(new Object[] { "samgwenhao",123456 }); System.out.println(obj); // 打印一下这个对象的信息 // 获取所有的构造方法集合 Constructor con1[] = clazz.getDeclaredConstructors(); con1[0].setAccessible(true); //=================获取方法 处理================================================ System.out.println("*******************获取方法处理*******************"); //反射机制 方法的处理 //getMethod获取指定公有方法 参数1:方法名 参数2:参数类型集合 //getDeclaredMethod获取任意指定方法(包括私有,这时要设置setAccessible(true) ) Method method = clazz.getDeclaredMethod("getMsg", String.class); method.setAccessible(true);//获取权限 System.out.println("============method方法="+method); System.out.println(" method.getName获取方法名:"+method.getName()); String returnMsg = (String) method.invoke(obj, "obj"); System.out.println("处理结果返回内容:"+returnMsg); Object obj2 = clazz .getConstructor(new Class[] { String.class ,String.class}) .newInstance(new Object[] { "samgwenhao","zipcode" }); String returnMsg2 = (String) method.invoke(obj2, "obj2"); System.out.println("处理结果返回内容:"+returnMsg2); // 通过默认无参构造方法创建一个新的对象 Constructor con3 = clazz.getDeclaredConstructor(new Class[] {}); con3.setAccessible(true); // 设置可访问的权限 Object obj3 = con3.newInstance(new Object[] {}); String returnMsg3 = (String) method.invoke(obj3, "obj3"); System.out.println("处理结果返回内容:"+returnMsg3); //获取方法集合,用法同上 //getMethod获取指定公有方法集合; //getDeclaredMethods获取任意指定方法集合(包括私有,这时要设置setAccessible(true) ) Method[] methods = clazz.getDeclaredMethods(); for(int i=0;i<methods.length;i++){ methods[i].setAccessible(true); System.out.println("============methods["+i+"]="+methods[i] //同 toGenericString 方法 +"\n\t methods[i].getName():"+methods[i].getName() +"\n\t methods[i].getModifiers():"+Modifier.toString(methods[i].getModifiers()) // +"\n\t methods[i].getAnnotation:"+methods[i].getAnnotation(Annotation.class) +"\n\t methods[i].toGenericString():"+methods[i].toGenericString() ); } // System.out.println("============methods[0]=" + methods[0] // + " methods[1]=" + methods[1]); Class<?>[] clazz2 = methods[0].getParameterTypes(); System.out.println("============clazz2[0]=" + clazz2 + " methods[1].getName=" + methods[1].getName()); //==============字段属性处理方法================================================ System.out.println("*******************字段属性处理方法*******************"); //public Field getDeclaredField(String name)获取任意指定名字的成员 //public Field[] getDeclaredFields() 获取所有的成员变量 //public Field getField(String name)获取任意public成员变量 //public Field[] getFields() 获取所有的public成员变量 Field field = clazz.getDeclaredField("add"); field.setAccessible(true); System.out.println("============获取成员变量:field="+field+"; field.getName()="+field.getName()); Field[] fields = clazz.getDeclaredFields(); for(int i=0;i<fields.length;i++){ fields[i].setAccessible(true); System.out.println("============获取成员变量:" +"\n\t fields["+i+"]" +fields[i] //同toGenericString方法 +"\n\t fields.getName()="+fields[i].getName() // 字段名 add +"\n\t fields[i].getType():"+fields[i].getType()//返回类型 class java.lang.String +"\n\t fields[i].toGenericString():"+fields[i].toGenericString() //字段的定义 private java.lang.String com.swh.xml.entity.AddressReflect.add +"\n\t fields[i].getModifiers():"+Modifier.toString(fields[i].getModifiers())//返回字段的修饰符 ); } //=================给成员变量赋值 ,注意:成员变量必须实现set方法========================== System.out.println("*******************给成员变量赋值*******************"); Field[] _fields = clazz.getDeclaredFields(); Constructor _con = clazz.getDeclaredConstructor(new Class[] {}); _con.setAccessible(true); // 设置可访问的权限(因此样例的无参构造函数是私有的) Object _obj = _con.newInstance(new Object[] {}); for(Field _field : _fields){ // _fields[i].setAccessible(true); // System.out.println("============获取成员变量:fields.getName()="+fields[i].getName()+" ; fields[i].getType():"+fields[i].getType()); //构建方法名 setXXX String fieldName = _field.getName() ; String firstLetter = fieldName.substring(0, 1).toUpperCase(); String setMethodName = "set" + firstLetter + fieldName.substring(1); String getMethodName = "get" + firstLetter + fieldName.substring(1); //获取指定方法名 setXXX 和 参数类型 的方法 Method setMethod = clazz.getMethod(setMethodName, _field.getType()); Method getMethod = clazz.getMethod(getMethodName);//或用下面的方法 // Method getMethod = clazz.getMethod(getMethodName,new Class[] {}); if(String.class.isAssignableFrom(_field.getType())){ System.out.println("进入String.class _field.getType():"+_field.getType()); //调用setXXX方法 setMethod.invoke(_obj, "asdfas"); // String result = getMethod.invoke(_obj, new Object[]{}); }else if(boolean.class.isAssignableFrom(_field.getType())){ System.out.println("进入boolean.class _field.getType():"+_field.getType()); //调用setXXX方法 setMethod.invoke(_obj, true); // String result = getMethod.invoke(_obj, new Object[]{}); }else if(Boolean.class.isAssignableFrom(_field.getType())){ System.out.println("进入Boolean.class _field.getType():"+_field.getType()); //调用setXXX方法 setMethod.invoke(_obj, true); // String result = getMethod.invoke(_obj, new Object[]{}); }else if(int.class.isAssignableFrom(_field.getType())){ System.out.println("进入int.class _field.getType():"+_field.getType()); //调用setXXX方法 setMethod.invoke(_obj, 123); // String result = getMethod.invoke(_obj, new Object[]{}); }else if(Integer.class.isAssignableFrom(_field.getType())){ System.out.println("进入Integer.class _field.getType():"+_field.getType()); //调用setXXX方法 setMethod.invoke(_obj, 123); // String result = getMethod.invoke(_obj, new Object[]{}); }else{ System.out.println("解析 _field.getType() 类型出错了"); } } String result = (String) clazz.getMethod("toString").invoke(_obj); System.out.println("返回结果 result:"+result); //=================给实现了set方法的成员变量赋值 ========================== System.out.println("*******************给实现了set方法的成员变量赋值*******************"); Method[] methods_ = clazz.getDeclaredMethods(); for(Method method_ : methods_){ // method_.setAccessible(true);//为true则可以访问private方法,默认为false String methodName = method_.getName(); if(methodName.startsWith("set")){ Method setMethod = clazz.getMethod(methodName,method_.getParameterTypes()[0]); // Method setMethod = clazz.getMethod(methodName,(Class) method_.getGenericParameterTypes()[0]); if(String.class.isAssignableFrom(method_.getParameterTypes()[0])){ System.out.println("进入String.class _field.getType():"+method_.getParameterTypes()[0]); //调用setXXX方法 setMethod.invoke(_obj, "asdfas"); }else if(boolean.class.isAssignableFrom(method_.getParameterTypes()[0])){ System.out.println("进入boolean.class _field.getType():"+method_.getParameterTypes()[0]); //调用setXXX方法 setMethod.invoke(_obj, true); }else if(Boolean.class.isAssignableFrom(method_.getParameterTypes()[0])){ System.out.println("进入Boolean.class _field.getType():"+method_.getParameterTypes()[0]); //调用setXXX方法 setMethod.invoke(_obj, true); }else if(int.class.isAssignableFrom(method_.getParameterTypes()[0])){ System.out.println("进入int.class _field.getType():"+method_.getParameterTypes()[0]); //调用setXXX方法 setMethod.invoke(_obj, 123); }else if(Integer.class.isAssignableFrom(method_.getParameterTypes()[0])){ System.out.println("进入Integer.class _field.getType():"+method_.getParameterTypes()[0]); //调用setXXX方法 setMethod.invoke(_obj, 123); }else{ System.out.println("解析 _field.getType() 类型出错了"); } } } String result2 = (String) clazz.getMethod("toString").invoke(_obj); System.out.println("返回结果 result:"+result2); } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } }AddressReflect 实体:
public class AddressReflect { private String add; private String zipcode; private Integer num ; private static boolean flag ; private AddressReflect(){ System.out.println("进入无参构造方法"); } public AddressReflect(String add, String zipcode) { this.add = add; this.zipcode = zipcode; System.out.println(toString()); } @SuppressWarnings("unused") private AddressReflect(String add,Integer num) { this.add = add; this.num = num ; System.out.println(toString()); } @Override public String toString() { return "Address{" + "add='" + add + '\'' + ", zipcode='" + zipcode + '\'' + ",num="+num+",flag="+flag+"}"; } private String getMsg(String content){ return "getMsg = "+content ; } public String getAdd() { return add; } public void setAdd(String add) { this.add = add; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public Integer getNum() { return num; } public void setNum(Integer num) { this.num = num; } public boolean getFlag() { return flag; } @SuppressWarnings("static-access") public void setFlag(boolean flag) { this.flag = flag; } }
运行效果:
********************获取反射对象******************** ============clazz=class com.swh.xml.entity.AddressReflect ********************获取构造方法 并执行******************** Address{add='samgwenhao', zipcode='null',num=123456,flag=false} Address{add='samgwenhao', zipcode='null',num=123456,flag=false} *******************获取方法处理******************* ============method方法=private java.lang.String com.swh.xml.entity.AddressReflect.getMsg(java.lang.String) method.getName获取方法名:getMsg 处理结果返回内容:getMsg = obj Address{add='samgwenhao', zipcode='zipcode',num=null,flag=false} 处理结果返回内容:getMsg = obj2 进入无参构造方法 处理结果返回内容:getMsg = obj3 ============methods[0]=public java.lang.String com.swh.xml.entity.AddressReflect.toString() methods[i].getName():toString methods[i].getModifiers():public methods[i].toGenericString():public java.lang.String com.swh.xml.entity.AddressReflect.toString() ============methods[1]=private java.lang.String com.swh.xml.entity.AddressReflect.getMsg(java.lang.String) methods[i].getName():getMsg methods[i].getModifiers():private methods[i].toGenericString():private java.lang.String com.swh.xml.entity.AddressReflect.getMsg(java.lang.String) ============methods[2]=public java.lang.String com.swh.xml.entity.AddressReflect.getAdd() methods[i].getName():getAdd methods[i].getModifiers():public methods[i].toGenericString():public java.lang.String com.swh.xml.entity.AddressReflect.getAdd() ============methods[3]=public void com.swh.xml.entity.AddressReflect.setAdd(java.lang.String) methods[i].getName():setAdd methods[i].getModifiers():public methods[i].toGenericString():public void com.swh.xml.entity.AddressReflect.setAdd(java.lang.String) ============methods[4]=public java.lang.String com.swh.xml.entity.AddressReflect.getZipcode() methods[i].getName():getZipcode methods[i].getModifiers():public methods[i].toGenericString():public java.lang.String com.swh.xml.entity.AddressReflect.getZipcode() ============methods[5]=public void com.swh.xml.entity.AddressReflect.setZipcode(java.lang.String) methods[i].getName():setZipcode methods[i].getModifiers():public methods[i].toGenericString():public void com.swh.xml.entity.AddressReflect.setZipcode(java.lang.String) ============methods[6]=public java.lang.Integer com.swh.xml.entity.AddressReflect.getNum() methods[i].getName():getNum methods[i].getModifiers():public methods[i].toGenericString():public java.lang.Integer com.swh.xml.entity.AddressReflect.getNum() ============methods[7]=public void com.swh.xml.entity.AddressReflect.setNum(java.lang.Integer) methods[i].getName():setNum methods[i].getModifiers():public methods[i].toGenericString():public void com.swh.xml.entity.AddressReflect.setNum(java.lang.Integer) ============methods[8]=public boolean com.swh.xml.entity.AddressReflect.getFlag() methods[i].getName():getFlag methods[i].getModifiers():public methods[i].toGenericString():public boolean com.swh.xml.entity.AddressReflect.getFlag() ============methods[9]=public void com.swh.xml.entity.AddressReflect.setFlag(boolean) methods[i].getName():setFlag methods[i].getModifiers():public methods[i].toGenericString():public void com.swh.xml.entity.AddressReflect.setFlag(boolean) ============clazz2[0]=[Ljava.lang.Class;@2e4f7bc2 methods[1].getName=getMsg *******************字段属性处理方法******************* ============获取成员变量:field=private java.lang.String com.swh.xml.entity.AddressReflect.add; field.getName()=add ============获取成员变量: fields[0]private java.lang.String com.swh.xml.entity.AddressReflect.add fields.getName()=add fields[i].getType():class java.lang.String fields[i].toGenericString():private java.lang.String com.swh.xml.entity.AddressReflect.add fields[i].getModifiers():private ============获取成员变量: fields[1]private java.lang.String com.swh.xml.entity.AddressReflect.zipcode fields.getName()=zipcode fields[i].getType():class java.lang.String fields[i].toGenericString():private java.lang.String com.swh.xml.entity.AddressReflect.zipcode fields[i].getModifiers():private ============获取成员变量: fields[2]private java.lang.Integer com.swh.xml.entity.AddressReflect.num fields.getName()=num fields[i].getType():class java.lang.Integer fields[i].toGenericString():private java.lang.Integer com.swh.xml.entity.AddressReflect.num fields[i].getModifiers():private ============获取成员变量: fields[3]private static boolean com.swh.xml.entity.AddressReflect.flag fields.getName()=flag fields[i].getType():boolean fields[i].toGenericString():private static boolean com.swh.xml.entity.AddressReflect.flag fields[i].getModifiers():private static *******************给成员变量赋值******************* 进入无参构造方法 进入 String.class _field.getType():class java.lang.String 进入 String.class _field.getType():class java.lang.String 进入 Integer.class _field.getType():class java.lang.Integer 进入 boolean.class _field.getType():boolean 返回结果 result:Address{add='asdfas', zipcode='asdfas',num=123,flag=true} *******************给实现了set方法的成员变量赋值******************* 进入 String.class _field.getType():class java.lang.String 进入 String.class _field.getType():class java.lang.String 进入 Integer.class _field.getType():class java.lang.Integer 进入 boolean.class _field.getType():boolean 返回结果 result:Address{add='asdfas', zipcode='asdfas',num=123,flag=true}