通过java的反射来获取对象方法和设置对象的属性值:
package com.reflect;
public class Car {
private String brand;
private String color;
private int maxSpeed;
//1、默认构造函数
public Car(){
System.out.println("init car!");
}
//2、带参构造函数
public Car(String brand, String color, int maxSpeed){
this.brand = brand;
this.color = color;
this.maxSpeed = maxSpeed;
}
//3、未带参的方法
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 com.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
public class CarTest {
/*
* Constructor:获取所有构造函数的反射类
* Method:获取所有类方法的反射类
* */
public static Car initDefaultConst() throws Throwable
{
//1.通过类装载器获取Car类对象
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.reflect.Car");
//2.获取类的默认构造器对象并实例化Car
Constructor cons = clazz.getDeclaredConstructor((Class[])null);
Car car = (Car)cons.newInstance();
//3.通过反射方法设置属性
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 Car initByParamConst() throws Throwable {
//1.通过类装载器获取Car类对象
ClassLoader loader = Thread.currentThread().getContextClassLoader();
Class clazz = loader.loadClass("com.reflect.Car");
//2.获取类的带有参数的构造器对象
Constructor cons = clazz.getDeclaredConstructor(new Class[]{String.class, String.class, int.class});
//3.使参数的构造器对象实例化Car
Car car = (Car)cons.newInstance(new Object[]{"宝马","骚红",180});
return car;
}
public static void main(String[] args) throws Throwable {
Car car1 = initDefaultConst();
Car car2 = initByParamConst();
car1.introduce();
car2.introduce();
}
}
显示结果:
init car!
brand:奔驰;color:粉红;maxSpeed:200
brand:宝马;color:骚红;maxSpeed:180
注:该代码为本人学习过程中的实验代码,谈不上原创,如有侵权请指出第一时间改正