Java运行通过程序化的方式间接对Class进行操作,Class文件由类装载期装载后,在
JVM中形成一份描述Class结构的元信息,通过对该元信息对象,可以获得Class的结构信息,如
构造函数,属性,方法等,java允许用户用这个Class相关的元信息对象间接调用
class对象的功能。
如下一个类Car,和利用
反射机制调用他的类ReflectTest
package reflect;
//实体类
public class Car {
private String brand;
private String color;
private int maxSpeed;
/**
* 构造方法
*/
public Car() {
// TODO Auto-generated constructor stub
}
/**
* 无参构造方法
*/
public Car(String brand,String color,int maxSpeed){
this.brand=brand;
this.color=color;
this.maxSpeed=maxSpeed;
}
/**
* 无参方法
* @return
*/
public void introduce(){
System.out.println("brand="+brand+";color="+color+";maxSpeed="+maxSpeed);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getMaxSpeed() {
return maxSpeed;
}
public void setMaxSpeed(int maxSpeed) {
this.maxSpeed = maxSpeed;
}
}
package reflect;
//反射调用类
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.omg.CORBA.Current;
public class ReflectTest {
public static Car initByDefaultConst() throws Throwable {
//通过类加载器加载类对象
ClassLoader loader =Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("reflect.Car");
//获取类的默认构造器,构造类
Constructor cons = clazz.getConstructor();
Car car = (Car) cons.newInstance();
//通过反射方法设置属性
Method setBrand = clazz.getMethod("setBrand", String.class);
setBrand.invoke(car, "玛莎拉蒂");
Method setColor= clazz.getMethod("setColor", String.class);
setColor.invoke(car, "红色");
Method setMaxSpeed =clazz.getMethod("setMaxSpeed", int.class);
setMaxSpeed.invoke(car, 200);
return car;
}
public static void main(String[] args) throws Throwable {
Car car =ReflectTest.initByDefaultConst();
car.introduce();
}
}