1.car.java
1 PackageCom.jike.spring.chapter03.reflect;2 3 Public classCar {4 PrivateString brand;5 6 PrivateString color;7 8 Private intmaxspeed;9 Ten //1. Default constructors One PublicCar () { ASystem.out.println ("Init car!!"); - } - the //2. With parameter constructors - PublicCar (String brand,string color,intmaxspeed) { - This. Brand =brand; - This. color =color; + This. Maxspeed =maxspeed; - } + A //3. Methods with no Parameters at Public voidintroduce () { -System.out.println ("Brand: +brand+"; color: "+color+"; Maxspeed: "+maxspeed); - } - - PublicString Getbrand () { - returnbrand; in } - to Public voidSetbrand (String brand) { + This. Brand =brand; - } the * PublicString GetColor () { $ returncolor;Panax Notoginseng } - the Public voidsetcolor (String color) { + This. color =color; A } the + Public intgetmaxspeed () { - returnmaxspeed; $ } $ - Public voidSetmaxspeed (intmaxspeed) { - This. Maxspeed =maxspeed; the } -}
2.reflecttest.java
1 PackageCom.jike.spring.chapter03.reflect;2 3 ImportJava.lang.reflect.Constructor;4 ImportJava.lang.reflect.Method;5 6 7 Public classReflecttest {8 9 Ten Public StaticCar Initbydefaultconst ()throwsThrowable One { A //1. Get the car class object through the class loader -ClassLoader loader =Thread.CurrentThread (). Getcontextclassloader (); -Class clazz = Loader.loadclass ("Com.jike.spring.chapter03.reflect.Car"); the - //2. Gets the default constructor object for the class and instantiates car -Constructor cons = Clazz.getdeclaredconstructor ((class[])NULL); -Car car =(Car) cons.newinstance (); + - //3. Setting properties by Reflection method +Method Setbrand = Clazz.getmethod ("Setbrand", String.class); ASetbrand.invoke (Car, "Mercedes"); atMethod SetColor = Clazz.getmethod ("SetColor", String.class); -Setcolor.invoke (Car, "black"); -Method setmaxspeed = Clazz.getmethod ("Setmaxspeed",int.class); -Setmaxspeed.invoke (car,200); - returncar; - } in - Public StaticCar Initbyparamconst ()throwsthrowable{ to //1. Get the car class object through the class loader +ClassLoader loader =Thread.CurrentThread (). Getcontextclassloader (); -Class clazz = Loader.loadclass ("Com.jike.spring.chapter03.reflect.Car"); the * //2. Get the constructor object with parameters for the class $Constructor cons = Clazz.getdeclaredconstructor (NewClass[]{string.class, String.class,int.class});Panax Notoginseng - //3. Instantiate the constructor object for the argument car theCar car = (car) cons.newinstance (Newobject[]{"BMW", "Red", 180}); + returncar; A } the + Public Static voidMain (string[] args)throwsThrowable { -Car car1 =initbydefaultconst (); $Car car2 =initbyparamconst (); $ car1.introduce (); - car2.introduce (); - } the}
2.sprng-ioc-java Reflection Example