JAVA反射机制是在运行状态中对于任意一个类都能够得到这个类的所有属性和方法;对于任意一个对象都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制
概括一下:
反射就是让你可以通过名称来得到对象(类属性方法)的技术
例如我们可以通过类名来生成一个类的实例;
知道了方法名就可以调用这个方法;知道了属性名就可以访问这个属性的值
获取类对应的Class对象
运用(已知对象)getClass():Object类中的方法每个类都拥有此方法
如: String str = new String();
Class strClass = strgetClass();运用(已知子类的class) ClassgetSuperclass():Class类中的方法返回该Class的父类的Class;运用(已知类全名):ClassforName() 静态方法运用(已知类): 类名class
通过类名来构造一个类的实例
a调用无参的构造函数:
Class newoneClass = ClassforName(类全名); newoneClassnewInstance();
b调用有参的构造函数我们可以自定义一个函数
public Object newInstance(String className Object[] args) throws Exception {
//args为参数数组
Class newoneClass = ClassforName(className); //得到参数的Class数组(每个参数的class组成的数组)由此来决定调用那个构造函数Class[] argsClass = new Class[argslength]; for (int i = j = argslength; i < j; i++) { argsClass[i] = args[i]getClass();
}
Constructor cons = newoneClassgetConstructor(argsClass); //根据argsClass选择函数return consnewInstance(args); //根据具体参数实例化对象
}
得到某个对象的属性
a非静态属性:首先得到class然后得到这个class具有的field然后以具体实例为参数调用这个field
public Object getProperty(Object owner String fieldName) throws Exception { Class ownerClass = ownergetClass();//首先得到class Field field = ownerClassgetField(fieldName); //然后得到这个class具有的field也可以通过getFields()得到所有的field Object property = fieldget(owner); //owner指出了取得那个实例的这个属性值如果这个属性是非公有的这里会报IllegalAccessException
return property;
}
b静态属性
只有最后一步不同由于静态属性属于这个类所以只要在这个类上调用这个field即可Object property = fieldget(ownerClass);
执行某对象的方法
public Object invokeMethod(Object owner String methodName Object[] args) throws Exception { Class ownerClass = ownergetClass(); //也是从class开始的//得到参数的class数组相当于得到参数列表的类型数组来取决我们选择哪个函数
Class[] argsClass = new Class[argslength]; for (int i = j = argslength; i < j; i++) { argsClass[i] = args[i]getClass();
}
//根据函数名和函数类型来选择函数
Method method = ownerClassgetMethod(methodName argsClass); return methodinvoke(owner args);//具体实例下具体参数值下调用此函数
}
执行类的静态方法
和上面的相似只是最后一行不需要指定具体实例
return methodinvoke(null args);
判断是否为某个类的实例
public boolean isInstance(Object obj Class cls) { return clsisInstance(obj);
}
测试bean类:SimpleBeanjava
Java代码
package comroyzhoubean;
public class SimpleBean {
private String name;
private String[] hobby;
public SimpleBean() {
}
public SimpleBean(String name String[] hobby) { thisname = name; thishobby = hobby;
}
public void setName(String name) {
thisname = name;
}
public String getName() {
return thisname;
}
public void setHobby(String[] hobby) {
thishobby = hobby;
}
public String[] getHobby() {
return thishobby;
}
public String toString() {
String returnValue = supertoString() + \n; returnValue += name:= + thisname + \n; if(thishobby != null) {
returnValue += hobby:;
for(String s : thishobby) { returnValue += s + ;
}
returnValue += \n;
}
return returnValue;
}
}
package comroyzhoubean;
public class SimpleBean {
private String name;
private String[] hobby;
public SimpleBean() {
}
public SimpleBean(String name String[] hobby) { thisname = name; thishobby = hobby;
}
public void setName(String name) {
thisname = name;
}
public String getName() {
return thisname;
}
public void setHobby(String[] hobby) {
thishobby = hobby;
}
public String[] getHobby() {
return thishobby;
}
public String toString() {
String returnValue = supertoString() + \n; returnValue += name:= + thisname + \n; if(thishobby != null) {
returnValue += hobby:;
for(String s : thishobby) { returnValue += s + ;
}
returnValue += \n;
}
return returnValue;
}
}
反射测试类:ReflectTestjava
Java代码
package comroyzhoubean;
import javalangreflectConstructor; import javalangreflectField; import javalangreflectMethod;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = SimpleBeanclass;
//使用无参构造函数实例化bean
SimpleBean sb = (SimpleBean)clazznewInstance(); Systemoutprintln(sb);
//使用有参构造函数实例化bean
Constructor constructor = clazzgetConstructor(new Class[]{Stringclass String[]class}); sb = (SimpleBean)constructornewInstance(new Object[]{royzhounew String[]{footballbasketball}}); Systemoutprintln(sb);
//为name字段设置值
Field field = clazzgetDeclaredField(name); fieldsetAccessible(true); //避免private不可访问抛出异常fieldset(sb royzhou); Systemoutprintln(modify name using Field:= + sbgetName() + \n);
//列出类SimpleBean的所有方法
Method[] methods = clazzgetDeclaredMethods(); Systemoutprintln(get methods of class SimpleBean:);
for(Method method : methods) {
if(setHobbyequals(methodgetName())) {
//动态调用类的方法来为hobby设置值
methodinvoke(sb new Object[]{new String[]{tennisfishing}});
}
Systemoutprintln(methodgetName());
}
Systemoutprintln(\nset by invoke Method); Systemoutprintln(sb);
}
}
package comroyzhoubean;
import javalangreflectConstructor; import javalangreflectField; import javalangreflectMethod;
public class ReflectTest {
public static void main(String[] args) throws Exception {
Class clazz = SimpleBeanclass;
//使用无参构造函数实例化bean
SimpleBean sb = (SimpleBean)clazznewInstance(); Systemoutprintln(sb);
//使用有参构造函数实例化bean
Constructor constructor = clazzgetConstructor(new Class[]{Stringclass String[]class}); sb = (SimpleBean)constructornewInstance(new Object[]{royzhounew String[]{footballbasketball}}); Systemoutprintln(sb);
//为name字段设置值
Field field = clazzgetDeclaredField(name); fieldsetAccessible(true); //避免private不可访问抛出异常fieldset(sb royzhou); Systemoutprintln(modify name using Field:= + sbgetName() + \n);
//列出类SimpleBean的所有方法
Method[] methods = clazzgetDeclaredMethods(); Systemoutprintln(get methods of class SimpleBean:);
for(Method method : methods) {
if(setHobbyequals(methodgetName())) {
//动态调用类的方法来为hobby设置值
methodinvoke(sb new Object[]{new String[]{tennisfishing}});
}
Systemoutprintln(methodgetName());
}
Systemoutprintln(\nset by invoke Method); Systemoutprintln(sb);
}
}
输出结果:
comroyzhoubeanSimpleBean@aef
name:=null
comroyzhoubeanSimpleBean@dfc
name:=royzhou
hobby:footballbasketball
modify name using Field:=royzhou
get methods of class SimpleBean:
setHobby
getHobby
getName
toString
setName
set by invoke Method
comroyzhoubeanSimpleBean@dfc
name:=royzhou
hobby:tennisfishing