Instance parsing of Java reflection mechanism

Source: Internet
Author: User


1. Get the object of the Java.lang.Class class of the access class you want to manipulate
2. Calling the class object method returns the method and property information of the Access class
3, using the reflection API to operate
After each class is loaded, a corresponding class object is generated for the class, which gives access to the class in the Java virtual machine, and there are typically three ways to get a class object in a Java program:

1. Calling the GetClass () method of an object is a method in object, so all classes can call this method

Person p= new Person ();

Class CLA = P.getclass ();

2. Call the class property of a category to get the class object

Class CLA = Person.class;

But this approach is to know the name of the class at compile time

3. Using the class forname () static method

The method needs to pass in a string parameter that is the full name of a class, for example

// the full path        of the user input class // Joptionpane helps to easily pop up a standard dialog box that asks the user for a value or notifies them        String classpath = Joptionpane.showinputdialog (null, "full path of the input class")        ; // classes are loaded according to the full path of the class, and the class object        is shipped back Class class1= Class.forName (classpath);

Be sure to fill in the full package name above, or throw a ClassNotFoundException exception

Summary: 2, 3 calls a class method to get the class object corresponding to it,

The code is more secure and the program is compiled to check that the class object being accessed exists

Program performance is higher, because these 2 ways do not need to call the method, so the performance of the program is better, most of us should use call GetClass () to get the class object

Instance:

Person.java

 PackageCom.pb.reflect.classinfo; Public classPerson {PrivateString name; PrivateString Gender; Private intAge ;  PublicString GetName () {returnname; }    Private voidsetName (String name) { This. Name =name; }    PrivateString Getgender () {returngender; }     Public voidSetgender (String gender) { This. Gender =gender; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicString toString () {return"Name is:" +name+ ", Age is:" +Age ; }    }

Reflectaction.java

 PackageCom.pb.reflect.classinfo;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method;ImportJavax.swing.JOptionPane;//gets the member methods and member properties of the class through the full path of the user input class Public classreflectaction {/*gets the class object way One * construction method, obtains the class object through the Class.forName () method*/     Publicreflectaction () {//the full path of the user input class//Joptionpane helps to easily pop up a standard dialog box that asks the user for a value or notifies themString classpath = Joptionpane.showinputdialog (NULL, "Enter the full path of the class"); Try {            //classes are loaded according to the full path of the class, and the class object is shipped backClass class1=Class.forName (classpath); //returns a collection of method objects through self-auditing of the class object's Class1Method[] Methods =Class1.getmethods (); //facilitates methods arrays, and outputs method informationSystem.out.println ("###### #获取方法信息 ##########");  for(Method meth:methods) {System.out.println (meth.tostring ()); } System.out.println ("###### #获取方法信息结束 ##########"); //returns a collection of member property objects using the self-class1 of the class objectfield[] fields=Class1.getdeclaredfields (); //facilitates the fields array and outputs the attribute informationSystem.out.println ("###### #获取属性信息 ##########");  for(Field field:fields) {System.out.println (field.tostring ()); } System.out.println ("###### #获取属性信息结束 ##########"); } Catch(ClassNotFoundException e) {e.printstacktrace (); }    }    /** Get Class object mode two: Using the object's GetClass () method*/     Publicreflectaction (person p) {Class Class1=P.getclass (); //returns a collection of method objects through self-auditing of the class object's Class1Method[] Methods =Class1.getmethods (); //facilitates methods arrays, and outputs method informationSystem.out.println ("###### #获取方法信息 ##########");  for(Method meth:methods) {System.out.println (meth.tostring ()); } System.out.println ("###### #获取方法信息结束 ##########"); //returns a collection of member property objects using the self-class1 of the class objectfield[] fields=Class1.getdeclaredfields (); //facilitates the fields array and outputs the attribute informationSystem.out.println ("###### #获取属性信息 ##########");  for(Field field:fields) {System.out.println (field.tostring ()); } System.out.println ("###### #获取属性信息结束 ##########"); }    }

Testreflection.java

 PackageCom.pb.reflect.classinfo;ImportJava.lang.reflect.Field;ImportJava.lang.reflect.Method; Public classtestreflection { Public Static voidMain (string[] args) {/*The first way to run the code: * Reflectaction RF = new Reflectaction ();*/                /*The second way to run the code: * Person p=new person (); Reflectaction RF = new Reflectaction (p);*/                /** Get the Class object way three, get through class attribute **/Class Class1= person.class; //returns a collection of method objects through self-auditing of the class object's Class1Method[] Methods =Class1.getmethods (); //facilitates methods arrays, and outputs method informationSystem.out.println ("###### #获取方法信息 ##########");  for(Method meth:methods) {System.out.println (meth.tostring ()); } System.out.println ("###### #获取方法信息结束 ##########"); //returns a collection of member property objects using the self-class1 of the class objectfield[] fields=Class1.getdeclaredfields (); //facilitates the fields array and outputs the attribute informationSystem.out.println ("###### #获取属性信息 ##########");  for(Field field:fields) {System.out.println (field.tostring ()); } System.out.println ("###### #获取属性信息结束 ##########"); }}

The 3rd method of recommendation

Instance parsing of Java reflection mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.