Java learning from scratch (reflection I), java from scratch

Source: Internet
Author: User

Java learning from scratch (reflection I), java from scratch
1. Is java a Dynamic Language?

Generally speaking, dynamic language means that the program structure or variable type can be changed while the program is running. From this point of view, JAVA and C ++ are not dynamic languages.

But JAVA has a very prominent Dynamic correlation mechanism: reflection. Through reflection, Java can load, explore, and use classes that are fully summed during compilation at runtime, generate their object entities, call their methods, or set values for properties. So Java is a semi-Dynamic Language.

Reflection concept:

In Java, the reflection mechanism means that all attributes and methods of a class can be known in the running state;

Any method of an object can be called;

This function of dynamically obtaining information and dynamically calling object methods is called the reflection mechanism of Java.

Ii. dynamic nature 2.1. dynamic nature
  • Generate an object instance at runtime;
  • Call methods during running;
  • Change attributes during runtime
2.2. functions implemented by the Java reflection mechanism
  • Determine the class to which any object belongs at runtime
  • Construct any class object at runtime
  • Determine the methods and attributes of any class at runtime
  • Call methods of any object at runtime
  • Generate dynamic proxy
2.3 Java reflection applications

In Java programs, many objects have two types at runtime: compile-time type and runtime type.

The type during compilation is determined by the type used to declare the object, and the type during runtime is determined by the Type actually assigned to the object.

For example:

Person p =new Student();

The compile-time type is Person, and the runtime is Student.

In addition, the program may also receive an externally passed-in Object at runtime. The compilation type of this Object is Object, but the program needs to call the method of the Object runtime type. To solve these problems, the program needs to discover the real information of objects and classes at runtime. However, if you cannot predict the classes that the object and class may belong to during compilation, the program only relies on the runtime information to discover the real information of the object and Class. reflection must be used at this time.

Iii. Java reflection API

The reflection API is used to generate information about classes, interfaces, or objects in the current Java virtual machine.

  • Class: the Core Class of reflection. You can obtain attributes, methods, and other content information of the Class.
  • Field Class: Java. lang. reflect. indicates the attributes of the class. You can obtain and set the attribute values in the class.
  • Method class: Java. lang. reflect. Indicates the method of the class. It can be used to obtain information about the method in the class or to execute the method.
  • Construcor class: Java. lang. reflect. Class constructor.
4. Obtain all methods and attributes

Person class

Package com. pb. reflect. classinfo; public class Person {private String name; private String gender; private int age; private Person () {//} public Person (String name, String gender, int age) {super (); this. name = name; this. gender = gender; this. age = age;} // getter, and setter Methods private String getName () {return name;} private void setName (String name) {this. name = name;} public String getGender () {return gender;} public void setGender (String gender) {this. gender = gender;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String toString () {return "name:" + name + "age:" + age ;}}

Use reflection:

Package com. pb. reflect. classinfo; import java. lang. reflect. constructor; import java. lang. reflect. field; import java. lang. reflect. method; import javax. swing. JOptionPane;/** obtain the member methods and attributes of the class through the full path of the class input by the user * Declared to obtain all private and public * 1. obtain the Class Object of the category Class * 2. call the Class Object method to return the class method and attribute information */public Class ReflectDemo {/** constructor */public ReflectDemo () {// full path of the user input class // use the String component String classpth = JOptionPane. showInputDialog (Null, "full path of input Class"); // use Class. the forName method returns the Class Object of the Class according to the full path of the input Class. forName (classpsomething); // use the Class Object's self-audit of the Class Object, return the Method object set method [] Method = CIA. getDeclaredMethods (); // return all methods System. out. println ("========= getting Method information =============="); for (method meth: Method) {// traverse the method array and output the method information System. out. println (meth. toString ();} System. out. println ("========= get method information end =============== "); // obtain attributes using the Class Object's self-audit of the Class Object, Returned Field [] field = fig. getDeclaredFields (); System. out. println ("========= getting member attribute information =============="); for (Field f: field) {System. out. println (f. toString ();} System. out. println ("========= get Member attribute information end ============== "); // obtain attributes using the Class Object's self-audit of the Class object, and return the Constructor constructor [] Constructor = groovy. getDeclaredConstructors (); System. out. println ("========= getting member Constructor information ============="); for (constructor constru: Constructor) {System. out. println (constru. toString ();} System. out. println ("========= get the end of the member constructor information ============");} catch (ClassNotFoundException e) {e. printStackTrace (); System. out. println ("Incorrect path input! ");}}}

Test class:

package com.pb.Reflect.classinfo;public class TestReflection {    public static void main(String[] args) {        ReflectDemo rd=new ReflectDemo();    }}

Enter com. pb. Reflect. classinfo. Person

Result:

========= Obtain method information ================= public java. lang. string com. pb. reflect. classinfo. person. getGender () public void com. pb. reflect. classinfo. person. setGender (java. lang. string) public int com. pb. reflect. classinfo. person. getAge () public void com. pb. reflect. classinfo. person. setAge (int) public java. lang. string com. pb. reflect. classinfo. person. toString () private java. lang. string com. pb. reflect. classinfo. person. getName () private void com. pb. reflect. classinfo. person. setName (java. lang. string) ======================================================= ========= private java. lang. string com. pb. reflect. classinfo. person. nameprivate java. lang. string com. pb. reflect. classinfo. person. genderprivate int com. pb. reflect. classinfo. person. age =============================================================== =========== private com. pb. reflect. classinfo. person () public com. pb. reflect. classinfo. person (java. lang. string, java. lang. string, int) ========= get the constructor information ================
5. Steps 5.1

Java. lang. reflect

  • Obtain the Java. lang. Class Object for the operation Class.
  • Call the Class Method
  • Use the reflection API to perform such operations.

 

5.2. How to obtain Class objects
  • Call the getClass () method of an object
Person p = new Person();Class cla=p.getClass();
  • Call the class attribute of a Class to obtain the class object corresponding to the Class.
Class cls=Person.class;
  • Use the forName () Static Method of the Class
Class linoleic = Class. forName ("full path of the Class ");
6. method 2 getClass () of the object

Person class. The constructor is public because the object is to be declared.

Package com. pb. reflect. classinfo; public class Person {private String name; private String gender; private int age; public Person () {//} public Person (String name, String gender, int age) {super (); this. name = name; this. gender = gender; this. age = age;} // getter, and setter Methods private String getName () {return name;} private void setName (String name) {this. name = name;} public String getGender () {return gender;} public void setGender (String gender) {this. gender = gender;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String toString () {return "name:" + name + "age:" + age ;}}

Use reflection:

Package com. pb. reflect. classinfo; import java. lang. reflect. constructor; import java. lang. reflect. field; import java. lang. reflect. method; import javax. swing. JOptionPane;/** obtain the member methods and attributes of the class through the full path of the class input by the user * Declared to obtain all private and public * 1. obtain the Class Object of the category Class * 2. call the method of the Class Object to return the method and attribute information of the Class */public ReflectDemo (Person p) {Class linoleic = p. getClass (); // use the Class Object's self-audit of the Class Object, return the Method object set method [] Method = CIA. getDeclaredMethods (); // return all methods System. out. println ("========= getting Method information =============="); for (method meth: Method) {// traverse the method array and output the method information System. out. println (meth. toString ();} System. out. println ("========= get method information end =============== "); // obtain attributes using the Class Object's self-audit of the Class object, and return the Field [] field = linoleic in the member attribute object set. getDeclaredFields (); System. out. println ("========= getting member attribute information =============="); for (Field f: field) {System. out. println (f. toString ();} System. out. println ("========= get Member attribute information end ============== "); // obtain attributes using the Class Object's self-audit of the Class object, and return the Constructor constructor [] Constructor = groovy. getDeclaredConstructors (); System. out. println ("========= getting member Constructor information ============="); for (constructor constru: Constructor) {System. out. println (constru. toString ();} System. out. println ("========= get the end of the member constructor information ============ ");}}

 

Test class

package com.pb.Reflect.classinfo;public class TestReflection {    public static void main(String[] args) {        Person p=new Person();        ReflectDemo rd=new ReflectDemo(p);    }}

 

Result: Same as above.

========= Obtain method information ================= public java. lang. string com. pb. reflect. classinfo. person. getGender () public void com. pb. reflect. classinfo. person. setGender (java. lang. string) public int com. pb. reflect. classinfo. person. getAge () public void com. pb. reflect. classinfo. person. setAge (int) public java. lang. string com. pb. reflect. classinfo. person. toString () private java. lang. string com. pb. reflect. classinfo. person. getName () private void com. pb. reflect. classinfo. person. setName (java. lang. string) ======================================================= ========= private java. lang. string com. pb. reflect. classinfo. person. nameprivate java. lang. string com. pb. reflect. classinfo. person. genderprivate int com. pb. reflect. classinfo. person. age =============================================================== ============ public com. pb. reflect. classinfo. person () public com. pb. reflect. classinfo. person (java. lang. string, java. lang. string, int) ========= get the end of the member constructor information ==============
VII. class attributes of the third method class

Same as Person

Test class:

Package com. pb. reflect. classinfo; import java. lang. reflect. constructor; import java. lang. reflect. field; import java. lang. reflect. method; public class TestReflection {public static void main (String [] args) {/* Method 2: Person p = new Person (); ReflectDemo rd = new ReflectDemo (p ); * // ** method 3. class Attribute */Class linoleic = Person. class; // use the Class Object's self-audit of the class Object, return the Method object set method [] Method = linoleic. getDeclaredMethods (); // return all methods System. out. println ("========= getting Method information =============="); for (method meth: Method) {// traverse the method array and output the method information System. out. println (meth. toString ();} System. out. println ("========= get method information end =============== "); // obtain attributes using the Class Object's self-audit of the Class object, and return the Field [] field = linoleic in the member attribute object set. getDeclaredFields (); System. out. println ("========= getting member attribute information =============="); for (Field f: field) {System. out. println (f. toString ();} System. out. println ("========= get Member attribute information end ============== "); // obtain attributes using the Class Object's self-audit of the Class object, and return the Constructor constructor [] Constructor = groovy. getDeclaredConstructors (); System. out. println ("========= getting member Constructor information ============="); for (constructor constru: Constructor) {System. out. println (constru. toString ();} System. out. println ("========= get the end of the member constructor information ============ ");}}

Result:

Same as above

========= Obtain method information ================= public java. lang. string com. pb. reflect. classinfo. person. getGender () public void com. pb. reflect. classinfo. person. setGender (java. lang. string) public int com. pb. reflect. classinfo. person. getAge () public void com. pb. reflect. classinfo. person. setAge (int) public java. lang. string com. pb. reflect. classinfo. person. toString () private java. lang. string com. pb. reflect. classinfo. person. getName () private void com. pb. reflect. classinfo. person. setName (java. lang. string) ======================================================= ========= private java. lang. string com. pb. reflect. classinfo. person. nameprivate java. lang. string com. pb. reflect. classinfo. person. genderprivate int com. pb. reflect. classinfo. person. age =============================================================== ============ public com. pb. reflect. classinfo. person () public com. pb. reflect. classinfo. person (java. lang. string, java. lang. string, int) ========= get the end of the member constructor information ==============

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.