The reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.
Class, a Class object will represent the properties of one of the classes, and there are three ways to get class classes
PackageJavase.first;/** * @authorFQH * @Date April 12, 2017: Morning 8:15:01*/ Public classEmployee {//properties, privatize properties, and provide methods to enable them to access through methods PrivateString name; Private intAge ; Private Doublesalary; Private Static Final intnumber=217;//Constants Private Static voidmethod1 () {System.out.println ("Static Method"); } Static{System.out.println ("Static Block"); } PublicEmployee () {}//Constructors PublicEmployee (String name,intAgeDoublesalary) { This. name=name; This. age=Age ; This. salary=salary; System.out.println ("Constructor"); } Public voidRaisesalary (Doublemultiple) { This. Salary *=multiple; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } Public Doublegetsalary () {returnsalary; } Public voidSetsalary (Doublesalary) { This. Salary =salary; } }View Code
@Test Public voidTestreflect () {Employee e=NewEmployee ("Fqh", 23, 5000); Class Class1=NULL; Class Class2=NULL; Class CLASS3=NULL; Try { //recommend thisClass1 = Class.forName ("Javase.first.Employee"); } Catch(ClassNotFoundException E1) {e1.printstacktrace (); } //The second KindClass2=employee.class; //Third Kindclass3=E.getclass (); System.out.println (Class1.getname ()+ "" +e.getname ());//through class. GetName () can get the class nameSystem.out.println (Class2.getname () + "" +e.getname ());//through class. GetName () can get the class nameSystem.out.println (Class3.getname () + "" +e.getname ());//through class. GetName () can get the class name } View Code
For example, when loading the JDBC driver class.forname ("Com.mysql.jdbc.Driver");
What if I need to get the property method of the class and so on?
@Test Public voidTestReflect2 ()throwsnosuchmethodexception, SecurityException, Illegalaccessexception, IllegalArgumentException, InvocationTargetException, Instantiationexception, nosuchfieldexception {Class Class1=NULL; Try { //recommend thisClass1 = Class.forName ("Javase.first.Employee"); } Catch(ClassNotFoundException E1) {e1.printstacktrace (); } System.out.println (Class1.getname ());//through class. GetName () can get the class nameSystem.out.println ("=============== This class property ==============="); //get all Properties, GetFields () is a way to get all publicfield[] Fields =Class1.getdeclaredfields (); for(Field f:fields) {//Permission Modifiers intMo =f.getmodifiers (); String Priv=modifier.tostring (MO); //Property Typeclass<?> type =F.gettype (); System.out.println (Priv+ "" + type.getname () + "" + f.getname () + ";"); } System.out.println ("=============== Method ==============="); Method[] Methods=Class1.getdeclaredmethods (); for(Method f:methods) {//Permission Modifiers intMo =f.getmodifiers (); String Priv=modifier.tostring (MO); //Property Typeclass<?> type =F.getreturntype (); System.out.println (Priv+ "" + type.getname () + "" + f.getname () + ";"); } System.out.println ("=============== calls method =============== by reflection mechanism"); Object obj=class1.newinstance (); Method Method= Class1.getmethod ("SetName", String.class); Method.invoke (obj,"FQH"); Method= Class1.getmethod ("GetName"); Method.invoke (obj); Employee e=(Employee) obj; System.out.println (E.getname ()); System.out.println ("=============== Modify property =============== by reflection mechanism"); Field field=class1.getdeclaredfield ("name"); //You can assign a value directly to a property of privateField.setaccessible (true);//Set property to modifiableField.set (obj, "Java Reflection mechanism"); System.out.println (Field.get (obj)); } View Code
Applying reflection to a factory method
InterfaceFruit { Public Abstract voideat ();}classAppleImplementsFruit { Public voideat () {System.out.println ("Apple"); }}classOrangeImplementsFruit { Public voideat () {System.out.println ("Orange"); }}classFactory { Public StaticFruit getinstance (String ClassName) {fruit F=NULL; Try{f=(Fruit) class.forname (ClassName). newinstance (); } Catch(Exception e) {e.printstacktrace (); } returnF; }}/*** For normal Factory mode when we add a subclass, we need to modify the factory class accordingly. When we add a lot of sub-classes, it can be very troublesome. * Java Factory mode can be referenced *Http://baike.xsoftlab.net/view/java-factory-pattern* * Now we use the reflection mechanism to implement Factory mode, you can add any number of subclasses without modifying the factory class. * * But it's still a bit cumbersome to know the full package name and class name, which can be done using the properties configuration file. * * Java read the Properties configuration file method can refer to *Http://baike.xsoftlab.net/view/java-read-the-properties-configuration-file * * @authorxsoftlab.net*/ Public classTestreflect { Public Static voidMain (string[] args)throwsException {fruit F= Factory.getinstance ("Net.xsoftlab.baike.Apple"); if(F! =NULL) {f.eat (); } }}View Code
Learn Java (quad) reflection from scratch