JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法,
对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为JAVA语言的反射机制。
这里通过两个简单类来测试,
一些定义什么的可以查阅文档或是API
//SimpleBean类
package wen.hui.reflect;
public class SimpleBean {
private String name;
private String[] hobby;
public SimpleBean() {
}
public SimpleBean(String name, String[] hobby) {
this.name = name;
this.hobby = hobby;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setHobby(String[] hobby) {
this.hobby = hobby;
}
public String[] getHobby() {
return this.hobby;
}
public String toString() {
String returnValue = super.toString() + "/n";
returnValue += "name=" + this.name + "/n";
if (this.hobby != null) {
returnValue += "hobby=";
for (String s : this.hobby) {
returnValue += s + ", ";
}
returnValue += "/n";
}
return returnValue;
}
public static void test(String str) {
System.out.println("My Test!!!!...." + str);
}
}
//ReflectTest类
package wen.hui.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] agrs) {
Class reflectClass = SimpleBean.class;
try {
/*
* 动态无参构造方法实例化一个SimpleBean对象
*/
SimpleBean sb = (SimpleBean)reflectClass.newInstance();
System.out.println(sb);
/*
* 使用有参构造函数实例化bean
*/
Constructor constructor = reflectClass.getConstructor(new Class[]{String.class, String[].class});
sb = (SimpleBean)constructor.newInstance(new Object[]{"royzhou",new String[]{"football","basketball"}});
System.out.println(sb);
/*
* 获取name字段的值
*/
SimpleBean sb1 = new SimpleBean("abc", new String[]{"a", "b"});
Field f = reflectClass.getDeclaredField("name");
f.setAccessible(true);
System.out.println("f.name = " + f.get(sb1));
/*
* 为name字段设置值
*/
Field field = reflectClass.getDeclaredField("name");
field.setAccessible(true); //避免private不可访问抛出异常
field.set(sb, "royzhou1985");
System.out.println("modify name using Field:=" + sb.getName() + "/n");
/*
* 返回SimpleBean的所有公共成员方法.
*/
Method m[];
m = reflectClass.getMethods();
for(int i=0; i
System.out.println(m[i].getName());
}
/*
* 动态调用类的方法来为hobby设置值
* 调用SimpelBean实例对象的setName方法来设值name属性的值
*/
SimpleBean sb2 = new SimpleBean("动态调用getName方法获取name属性", null);
for(int i=0; i
if(m[i].getName().equals("getName")) {
System.out.println(m[i].invoke(sb2, null));
}
}
/*
* 调用静态方法
*/
for(int i=0; i
if(m[i].getName().equals("test")) {
m[i].invoke(null, "传递参数");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
两个测试类讲解的东西有限, 更多请参考Java API文档..
主要用到的类有:
java.lang包下的: Object, Class
java.lang.reflect包下的所有类