JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
/**
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InstantiationException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*
* @desc class 反射对象描述类的语义结构,可以从类对象中获得构造函数,成员变量,方法
* 注解,修饰符等.
* 2.可以操纵类就像正常类的操作一样
*
*
*/
public static void testReflect() throws ClassNotFoundException,
NoSuchMethodException, SecurityException, InstantiationException,
IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
// 类路径
String className = "com.saber.reflect.model.Car";
// 获得类装载器ClassLoader
ClassLoader loader = Thread.currentThread().getContextClassLoader();
// 加载类
Class<?> clazz = loader.loadClass(className);
//使用Class 的静态变量生成 类
// Class<?> clazz = Class.forName(className);
// 获取无参构造器
Constructor<?> cons = clazz.getDeclaredConstructor();
// 获取有参构造器
// Constructor<?> cons = clazz.getDeclaredConstructor(String.class,
// String.class, Double.class);
//实例化对象
Car car = (Car) cons.newInstance();
//获取所有的属性
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
System.out.println(field);
}
//获取所有的方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
System.out.println(method);
}
//获得指定名称的方法
Method setBrand = clazz.getMethod("setBrand", String.class);
setBrand.invoke(car, "BMW");
Method setColor = clazz.getDeclaredMethod("setColor", String.class);
setColor.invoke(car, "white");
Method setPrice = clazz.getDeclaredMethod("setPrice", Double.class);
setPrice.invoke(car, 1000000.0);
System.out.println(car.toString());
}