本例简单描述下Java反射的实现:
Car.java
package cn.hafx.reflect;
public class Car
{
private String brand;
private String color;
private int maxSpeed;
public Car()
{
}
public Car(String brand, String color, int maxSpeed)
{
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
public void introduce()
{
System.out.println("Car [brand=" + brand + ", color=" + color + ", maxSpeed=" + maxSpeed
+ "]");
}
//setter getter
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;
}
}
反射类: ReflectTest.java
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest
{
@SuppressWarnings({"unchecked", "rawtypes"})
public static Car initByDefault()
throws ClassNotFoundException, SecurityException, NoSuchMethodException,
IllegalArgumentException, InstantiationException, IllegalAccessException,
InvocationTargetException
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("cn.hafx.reflect.Car");
Constructor cons = clazz.getDeclaredConstructor((Class[])null);
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, 1000);
return car;
}
public static void main(String[] args)
throws Exception
{
ReflectTest.initByDefault().introduce();
//反射实现目的相当于下面的代码
new Car("红旗","黑色",1000).introduce();
}
}