JAVA反射特点:程序动态执行时,可获取类,对象实例属性方法等。缺点是性能消耗大!
Java6.0 做优化后性能已不是瓶颈,cjlib是动态的生成字节码
Book类:
反射测试类:
package com.taobao.terminator.allen.JavaReflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectionTest {
public static Class cl = null;
public static Book book = null;
static {
book = new Book("hello", 1000);
cl = book.getClass();
}
/**
* 获取属性
* @param book
* @throws Exception
*/
public static void getProperty() throws Exception {
Field nField = cl.getDeclaredField("name");
Field aField = cl.getDeclaredField("address");
nField.setAccessible(true);//值为true 则指示反射的对象在使用时应该取消Java 语言访问检查
aField.setAccessible(true);
String name = (String)nField.get(book);
//如为静态属性,直接从cl里面取
String address = (String)aField.get(cl);
System.out.println("属性name:" + name + "属性address:" + address);
System.out.println("name:" + nField.getName() + "name属性类型:" + nField.getType()) ;
}
/**
* 执行方法
* @param param
* @throws Exception
*/
public static void getMethod(String param) throws Exception {
Class[] params = new Class[1];
params[0] = param.getClass();
Method nMethod = cl.getDeclaredMethod("checkName", params);
Method sMethod = cl.getDeclaredMethod("checkAddress", params);
System.out.println(nMethod.invoke(book, param));
System.out.println(sMethod.invoke(null, param));
}
/**
* 构造器生成实例,注意原子类型需要用包装类型封箱操作
* @param name
* @param id
* @throws Exception
*/
public static void getConstructor(String name,Integer id) throws Exception {
Object[] args = new Object[2];
args[0] = name;
args[1] = id;
Class[] params = new Class[2];
params[0] = name.getClass();
params[1] = id.getClass();
Constructor constructor = cl.getConstructor(params);
Book newBook = (Book)constructor.newInstance(args);
//同样可直接用反射生成新类ReflectionUtils.newInstance(job.getMapperClass(), job);
System.out.println("新名称:" + newBook.getName() + "新实例Id:" + newBook.getId());
}
public static void main(String[] args) {
try {
getProperty();
getMethod("world");
getConstructor("hello allen", 15000);
} catch (Exception e) {
e.printStackTrace();
}
}
}