反射机制:
反射(Reflection)能够让运行于JVM中的程序检测和修改运行时的行为。”这个概念常常会和内省(Introspection)混淆,以下是这两个术语在Wikipedia中的解释:
内省用于在运行时检测某个对象的类型和其包含的属性;
反射用于在运行时检测和修改某个对象的结构及其行为。
从它们的定义可以看出,内省是反射的一个子集。有些语言支持内省,但并不支持反射,如C++。
下面看反射的例子:
Person.java
package reflect;
/**
* Created with IntelliJ IDEA.
* User: ASUS
* Date: 14-7-10
* Time: 下午2:10
* To change this template use File | Settings | File Templates.
*/
public class Person {
public static final int MAX_LENGTH = 10;
public static final String BELONG = "MY";
public int age;
public String name;
public String address;
public Person() {
}
public Person(int age, String name) {
this.age = age;
this.name = name;
}
public Person(int age, String name, String address) {
this.age = age;
this.name = name;
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void doWork(String command) {
System.out.println("command==" + command);
}
public void doWork(String command, Boolean flag) {
if (flag) {
System.out.println("command==" + command);
} else {
System.out.println("command==" + command);
}
}
public String sayHello() {
return "I'm hello";
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person that = (Person) o;
if (age != that.age) return false;
if (!name.equals(that.name)) return false;
return true;
}
@Override
public int hashCode() {
int result = age;
result = 31 * result + name.hashCode();
return result;
}
}
ReflectionTest.java
package reflect;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.*;
/**
* Created with IntelliJ IDEA.
* User: ASUS
* Date: 14-7-10
* Time: 下午2:10
* To change this template use File | Settings | File Templates.
*/
public class ReflectionTest {
/**
* 通过反正调用某个对象的方法
*
* @throws Exception
*/
@Test
public void test8() throws Exception {
Person person = new Person();
System.out.println(person.getClass().getName());
Class personClass = (Class) Class.forName("reflect.Person");
Person person1 = personClass.newInstance();
System.out.println(person1.sayHello());
/**
* parameterTypes表示要调用函数的参数的class类型
* 是一个可变参数列表
* public Method getMethod(String name, Class>... parameterTypes)
*/
try {
Method doWorkMethod = personClass.getMethod("doWork", String.class);
String command = "never give up";
/**
* invoke函数的第一个参数是一个类的实例,表示要调用该对象的方法,第二个及以后的参数是
* 可变参数列表,表示要调用方法的参数
*/
doWorkMethod.invoke(person1, command);
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
/**
* 获取构造函数,并创建对象。
*/
@Test
public void test98() throws ClassNotFoundException, IllegalAccessException, InvocationTargetException, InstantiationException {
Class personClass = (Class) Class.forName("reflect.Person");
Constructor[] constructors = (Constructor[]) personClass.getConstructors();
int n = 0;
for (Constructor constructor : constructors) {
//构造函数的名字
System.out.println(n + "=" + constructor.getName());
//构造函数的参数的个数
System.out.println(n + "=ParameterCount=" + constructor.getParameterCount());
n++;
}
Person person = constructors[0].newInstance(12, "hello", "world");
System.out.println(person.getName() + " " + person.getAddress());
Person person1 = constructors[1].newInstance(15, "sdsd");
System.out.println(person1.getAge());
}
/**
* 得到某个类的所有属性
*/
@Test
public void test987() throws ClassNotFoundException, IllegalAccessException, InstantiationException {
Class personClass = (Class) Class.forName("reflect.Person");
Field[] fields = personClass.getFields();
for (Field field : fields) {
System.out.println(field.getName()); //字段的名称
System.out.println(field.getType().getName()); //字段的数据类型
int modifiers = field.getModifiers();
boolean isStatic = Modifier.isStatic(modifiers);
if (isStatic) {
/**
* 如果是静态字段,get方法的参数可以为null
*/
System.out.println(field.getName() + "是静态字段,value=" + field.get(null));
} else {
/**
* 如果是实例字段,obj对象是一个该实例字段所属的对象或一个实例
*/
System.out.println(field.getName() + "不是静态字段,value=" + field.get(personClass.newInstance()));
}
}
}
/**
* 得到一个类的所有方法
*/
@Test
public void test098() throws ClassNotFoundException {
Class personClass = (Class) Class.forName("reflect.Person");
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
int m = method.getModifiers();
if (Modifier.isPublic(m)) {
System.out.println(method.getName() + "是一个public方法");
}
Annotation[] annotations = method.getDeclaredAnnotations();
System.out.println("===S===");
for (Annotation annotation : annotations) {
System.out.println(annotation.toString());
}
System.out.println("===E===");
}
}
}
====END====