Java反射的用法

Class类

在Java中,每个class都有一个相应的Class对象。也就是说,当我们编写一个类,编译完成后,在生成的.class文件中,就会产生一个Class对象,用于表示这个类的类型信息。

反射

Java的反射主要就是使用class对象生成对应类的实例、调用类的方法等对操作。示例代码:

Car.java

public class Car {

	private String brand;

	private String color;

	private Integer maxSpeed;

	public Car() {
	}

	public Car(String brand, String color, Integer maxSpeed) {
		super();
		this.brand = brand;
		this.color = color;
		this.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 Integer getMaxSpeed() {
		return maxSpeed;
	}

	public void setMaxSpeed(Integer maxSpeed) {
		this.maxSpeed = maxSpeed;
	}

	@Override
	public String toString() {
		return "Car [brand=" + brand + ", color=" + color + ", maxSpeed="
				+ maxSpeed + "]";
	}

	public void testPrivate() {
		System.out.println("call testPrivate()");
	}

}

ReflectTest.java

public class RelectTest {

	public static void main(String[] args) throws ClassNotFoundException,
			InstantiationException, IllegalAccessException, SecurityException,
			NoSuchFieldException, NoSuchMethodException,
			IllegalArgumentException, InvocationTargetException {
		// 创建class,方法1
		Class<?> clazz = Class.forName("com.Car");
		// 创建class,方法2,相对来说,方法1更适合从配置中读取包的限定名字符串,避免了方法2中需要导包的操作
		clazz = Car.class;
		// 创建对象
		Car car = (Car) clazz.newInstance();
		// 获取所有的属性
		Field[] fields = clazz.getDeclaredFields();
		System.out.print("All fields:");
		for (Field field : fields) {
			System.out.print(field.getName() + ",");
		}
		System.out.println();
		// 获取所有的public属性
		Field[] publicFilds = clazz.getFields();
		System.out.print("All public fields:");
		for (Field field : publicFilds) {
			System.out.print(field.getName() + ",");
		}
		System.out.println();
		// 获取继承或接口中的所有方法
		Method[] methods = clazz.getMethods();
		System.out.println("All methods:");
		for (Method method : methods) {
			System.out.println(method.getReturnType() + " " + method.getName()
					+ "(" + displayClass(method.getParameterTypes()) + ")");
		}
		System.out.println();
		// 获取本类中的public, protected, private方法,不包括继承的方法
		Method[] selfMethods = clazz.getDeclaredMethods();
		System.out.println("All self methods:");
		for (Method method : selfMethods) {
			System.out.println(method.getReturnType() + " " + method.getName()
					+ "(" + displayClass(method.getParameterTypes()) + ")");
		}
		System.out.println();
		// 获取构造函数
		Constructor[] constructors = clazz.getDeclaredConstructors();
		System.out.println("All Constructor:");
		for (Constructor constructor : constructors) {
			System.out.println(constructor.getName() + "("
					+ displayClass(constructor.getParameterTypes()) + ")");
		}
		System.out.println();

		// 获取指定的属性
		Field brandField = clazz.getDeclaredField("brand");
		// 通过属性为字段赋值
		brandField.setAccessible(true);// 由于brand属性为private,必须设置覆盖java对该字段的访问控制检查
		brandField.set(car, "奔驰");
		System.out.println(car);

		// 获取指定的方法
		Method colorSetMethod = clazz.getDeclaredMethod("setColor",
				String.class);
		colorSetMethod.invoke(car, "黑色");
		System.out.println(car);

		Method testPrivateMethod = clazz.getDeclaredMethod("testPrivate");
		testPrivateMethod.invoke(car, null);

	}

	public static String displayClass(Class[] s) {
		StringBuilder sb = new StringBuilder();
		for (Class c : s) {
			if (sb.length() > 0)
				sb.append(", ");
			sb.append(c.getName());
		}
		return sb.toString();
	}

}
posted @ 2017-08-24 09:26  Acode  阅读(243)  评论(0编辑  收藏  举报
您是本站第访问量位访问者!