The reflection mechanism is widely used. Here's a simple note under
PackageCom.shone.ailin;ImportJava.lang.reflect.Constructor;ImportJava.lang.reflect.Field;Importjava.lang.reflect.InvocationTargetException;ImportJava.lang.reflect.Method; Public classReflectdemo { Public Static voidMain (string[] args)throwsException {printvar (); CreateInstance (); Printallvarname (); } //Print all member variable names Private Static voidPrintallvarname () {//TODO auto-generated Method StubPoint P =NewPoint (1,3); Field[] Fields=P.getclass (). Getdeclaredfields (); for(inti=0;i<fields.length;i++) {System.out.println ("var[" +i+ "]=" +fields[i].getname ()); } } //Print the value of a member variable Private Static voidPrintvar ()throwsnosuchfieldexception, SecurityException, IllegalArgumentException, illegalaccessexception {point P=NewPoint (1,4); Field FX= P.getclass (). Getdeclaredfield ("x"); Fx.setaccessible (true);//it has to be added here. Otherwise, an exception will be thrown. Because it is a private member variable, it requires a violent reflection intx = (int) Fx.get (p); System.out.println ("X=" +x); } //To create an instantiated object and invoke a method Private Static voidCreateInstance ()throwsException, SecurityException {Constructor<Point> con = point.class. GetConstructor (int.class,int.class); Try{Point instance= Con.newinstance (1,3); Method m= Instance.getclass (). Getdeclaredmethod ("Addcount",int.class,int.class); M.setaccessible (true); Try { intCount = (int) M.invoke (instance,2,7); System.out.println (count); } Catch(illegalaccessexception e) {e.printstacktrace (); } Catch(IllegalArgumentException e) {e.printstacktrace (); } Catch(InvocationTargetException e) {e.printstacktrace (); } } Catch(nosuchmethodexception e) {e.printstacktrace (); } Catch(SecurityException e) {e.printstacktrace (); } } }
Point class
PackageCom.shone.ailin; Public classPoint {Private intx; Public inty; PublicPoint (intXinty) {//TODO auto-generated Constructor stub Super(); This. x =x; This. y =y; } Private intAddcount (intXinty) {returnx+y; }}
Java Reflection Basics Application Notes