**********************Java反射机制学习笔记***********************
反射机制实现:
在运行时判断任意一个对象所属的类。
在运行时构造任意一个类的对象。
在运行时判断任意一个类所具有的成员变量和方法。
在运行时调用任意一个对象的方法
Reflection 是Java被视为动态(或准动态)语言的一个关键性质。这个机制允许程序在运行时透过Reflection APIs取得任何一个已知名称的class的内部信息,包括其modifiers(诸如public, static 等等)、superclass(例如Object)、实现之interfaces(例如Serializable),也包括fields和methods的所有信息,并可于运行时改变fields内容或调用methods
一般而言,开发者社群说到动态语言,大致认同的一个定义是:“程序运行时,允许改变程序结构或变量类型,这种语言称为动态语言”。从这个观点看,Perl,Python,Ruby是动态语言,C++,Java,C#不是动态语言
尽管在这样的定义与分类下Java不是动态语言,它却有着一个非常突出的动态相关机制:Reflection。这个字的意思是“反射、映象、倒影”,用在Java身上指的是我们可以于运行时加载、探知、使用编译期间完全未知的classes。换句话说,Java程序可以加载一个运行时才得知名称的class,获悉其完整构造(但不包括methods定义),并生成其对象实体、或对其fields设值、或唤起其methods。这种“看透class”的能力(the ability of the program to examine itself)被称为introspection(内省、内观、反省)。Reflection和introspection是常被并提的两个术语
在JDK中,主要由以下类来实现Java反射机制,这些类都位于java.lang.reflect包中
Class类:代表一个类。
Field 类:代表类的成员变量(成员变量也称为类的属性)。
Method类:代表类的方法。
Constructor 类:代表类的构造方法。
Array类:提供了动态创建数组,以及访问数组的元素的静态方法
在java.lang.Object 类中定义了getClass()方法,因此对于任意一个Java对象,都可以通过此方法获得对象的类型。Class类是Reflection API 中的核心类,它有以下方法
getName():获得类的完整名字。
getFields():获得类的public类型的属性。
getDeclaredFields():获得类的所有属性。
getMethods():获得类的public类型的方法。
getDeclaredMethods():获得类的所有方法。
getMethod(String name, Class[] parameterTypes):获得类的特定方法,name参数指定方法的名字,parameterTypes 参数指定方法的参数类型。
getConstructors():获得类的public类型的构造方法。
getConstructor(Class[] parameterTypes):获得类的特定构造方法,parameterTypes 参数指定构造方法的参数类型。
newInstance():通过类的不带参数的构造方法创建这个类的一个对象。
*当方法接受原生数据类型的时候,反射调用的时候必须转化成包装类
但是Jdk5.0之后就已经具备自动包装的功能。因此只需知道即可。
实例两则:
packagecom.sy.reflection;importjava.lang.reflect.Field;importjava.lang.reflect.Method;publicclassReflectTester
{publicObject copy(Object object)throwsException
{//获得对象的类型Class>classType=object.getClass();
System.out.println("Class:"+classType.getName());//通过默认构造方法创建一个新的对象Object objectCopy=classType.getConstructor(newClass[] {}).newInstance(newObject[] {});//获得对象的所有属性Field fields[]=classType.getDeclaredFields();for(inti=0; i
{
Field field=fields[i];
String fieldName=field.getName();
String firstLetter=fieldName.substring(0,1).toUpperCase();//获得和属性对应的getXXX()方法的名字String getMethodName="get"+firstLetter+fieldName.substring(1);//获得和属性对应的setXXX()方法的名字String setMethodName="set"+firstLetter+fieldName.substring(1);//获得和属性对应的getXXX()方法Method getMethod=classType.getMethod(getMethodName,newClass[] {});//获得和属性对应的setXXX()方法Method setMethod=classType.getMethod(setMethodName,newClass[] { field.getType() });//调用原对象的getXXX()方法Object value=getMethod.invoke(object,newObject[] {});
System.out.println(fieldName+":"+value);//调用拷贝对象的setXXX()方法setMethod.invoke(objectCopy,newObject[] { value });
}returnobjectCopy;
}publicstaticvoidmain(String[] args)throwsException
{
Customer customer=newCustomer("Tom",21);
customer.setId(newLong(1));
Customer customerCopy=(Customer)newReflectTester().copy(customer);
System.out.println("Copy information:"+customerCopy.getId()+""+customerCopy.getName()+""+customerCopy.getAge());
}
}classCustomer
{privateLong id;privateString name;privateintage;publicCustomer()
{
}publicCustomer(String name,intage)
{this.name=name;this.age=age;
}publicLong getId()
{returnid;
}publicvoidsetId(Long id)
{this.id=id;
}publicString getName()
{returnname;
}publicvoidsetName(String name)
{this.name=name;
}publicintgetAge()
{returnage;
}publicvoidsetAge(intage)
{this.age=age;
}
}packagecom.sy.reflection;importjava.lang.reflect.Method;publicclassInvokeTester
{publicintadd(intparam1,intparam2)
{returnparam1+param2;
}publicString echo(String msg)
{return"echo:"+msg;
}publicstaticvoidmain(String[] args)throwsException
{
Class>classType=InvokeTester.class;
Object invokeTester=classType.newInstance();//Object invokeTester = classType.getConstructor(new//Class[]{}).newInstance(new Object[]{});//调用InvokeTester对象的add()方法Method addMethod=classType.getMethod("add",newClass[] {int.class,int.class});
Object result=addMethod.invoke(invokeTester,newObject[] {newInteger(100),newInteger(200) });
System.out.println((Integer) result);//调用InvokeTester对象的echo()方法Method echoMethod=classType.getMethod("echo",newClass[] { String.class});
result=echoMethod.invoke(invokeTester,newObject[] {"Hello"});
System.out.println((String) result);
}
}
施杨出品,转载注明:www.cnblogs.com/shiyangxt