1.Car.java
1 package com.jike.spring.chapter03.reflect; 2 3 public class Car { 4 private String brand; 5 6 private String color; 7 8 private int maxSpeed; 9 10 //1.默认构造函数 11 public Car(){ 12 System.out.println("init car!!"); 13 } 14 15 //2.带参构造函数 16 public Car(String brand,String color,int maxSpeed){ 17 this.brand = brand; 18 this.color = color; 19 this.maxSpeed = maxSpeed; 20 } 21 22 //3.未带参的方法 23 public void introduce() { 24 System.out.println("brand:"+brand+";color:"+color+";maxSpeed:"+maxSpeed); 25 } 26 27 public String getBrand() { 28 return brand; 29 } 30 31 public void setBrand(String brand) { 32 this.brand = brand; 33 } 34 35 public String getColor() { 36 return color; 37 } 38 39 public void setColor(String color) { 40 this.color = color; 41 } 42 43 public int getMaxSpeed() { 44 return maxSpeed; 45 } 46 47 public void setMaxSpeed(int maxSpeed) { 48 this.maxSpeed = maxSpeed; 49 } 50 }
2.ReflectTest.java
1 package com.jike.spring.chapter03.reflect; 2 3 import java.lang.reflect.Constructor; 4 import java.lang.reflect.Method; 5 6 7 public class ReflectTest { 8 9 10 public static Car initByDefaultConst() throws Throwable 11 { 12 //1.通过类装载器获取Car类对象 13 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 14 Class clazz = loader.loadClass("com.jike.spring.chapter03.reflect.Car"); 15 16 //2.获取类的默认构造器对象并实例化Car 17 Constructor cons = clazz.getDeclaredConstructor((Class[])null); 18 Car car = (Car)cons.newInstance(); 19 20 //3.通过反射方法设置属性 21 Method setBrand = clazz.getMethod("setBrand",String.class); 22 setBrand.invoke(car,"奔驰"); 23 Method setColor = clazz.getMethod("setColor",String.class); 24 setColor.invoke(car,"黑色"); 25 Method setMaxSpeed = clazz.getMethod("setMaxSpeed",int.class); 26 setMaxSpeed.invoke(car,200); 27 return car; 28 } 29 30 public static Car initByParamConst() throws Throwable{ 31 //1.通过类装载器获取Car类对象 32 ClassLoader loader = Thread.currentThread().getContextClassLoader(); 33 Class clazz = loader.loadClass("com.jike.spring.chapter03.reflect.Car"); 34 35 //2.获取类的带有参数的构造器对象 36 Constructor cons = clazz.getDeclaredConstructor(new Class[]{String.class,String.class,int.class}); 37 38 //3.使参数的构造器对象实例化Car 39 Car car = (Car)cons.newInstance(new Object[]{"宝马","红色",180}); 40 return car; 41 } 42 43 public static void main(String[] args) throws Throwable { 44 Car car1 = initByDefaultConst(); 45 Car car2 = initByParamConst(); 46 car1.introduce(); 47 car2.introduce(); 48 } 49 }
时间: 2024-10-24 14:56:28