使用反射类、Class类获取指定的构造器并实例化对象
1 package com.test; 2 3 public class Car { 4 5 private String brand; 6 private String color; 7 private int maxSpeed; 8 9 public Car(){} 10 11 public Car(String brand, String color, int maxSpeed) { 12 super(); 13 this.brand = brand; 14 this.color = color; 15 this.maxSpeed = maxSpeed; 16 } 17 18 public String getBrand() { 19 return brand; 20 } 21 22 public void setBrand(String brand) { 23 this.brand = brand; 24 } 25 26 public String getColor() { 27 return color; 28 } 29 30 public void setColor(String color) { 31 this.color = color; 32 } 33 34 public int getMaxSpeed() { 35 return maxSpeed; 36 } 37 38 public void setMaxSpeed(int maxSpeed) { 39 this.maxSpeed = maxSpeed; 40 } 41 42 @Override 43 public String toString() { 44 return "Car [brand=" + brand + ", color=" + color + ", maxSpeed=" 45 + maxSpeed + "]"; 46 } 47 48 }
1 package com.test; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Method; 5 public class ReflectTest { 6 7 public static Car initByDefaultConst() throws Throwable{ 8 //通过类转载器获取Car类对象 9 //ClassLoader loader = Thread.currentThread().getContextClassLoader(); 10 //Class clazz = loader.loadClass("com.test.Car"); 11 Class clazz = Class.forName("com.test.Car"); 12 13 //构造器器参数列表 14 Class[] cl = {String.class, String.class, int.class}; 15 16 //获取默认的构造器 17 //Constructor cons = clazz.getDeclaredConstructor(null); 18 19 //获取指定的带参数的构造器对象,并通过它实例化Car 20 Constructor cons = clazz.getDeclaredConstructor(cl); 21 //构造器参数 22 Object[] ps = {"红旗H7", "黑色", 200}; 23 //创建实例 24 Car car = (Car)cons.newInstance(ps); 25 26 //通过反射方法设置属性 27 /* Method setBrand = clazz.getMethod("setBrand", String.class); 28 setBrand.invoke(car, "红旗H7"); 29 Method setColor = clazz.getMethod("setColor", String.class); 30 setColor.invoke(car, "黑色"); 31 Method setMaxSpeed = clazz.getMethod("setMaxSpeed", int.class); 32 setMaxSpeed.invoke(car, 200);*/ 33 return car; 34 } 35 36 public static void main(String[] args) throws Throwable { 37 Car car = initByDefaultConst(); 38 System.out.println(car); 39 } 40 41 }