Java advanced reflection, java advanced reflection

Source: Internet
Author: User

Java advanced reflection, java advanced reflection

Class reflection

Class reflection: This is an advanced java technology. If you have learned this well, your java learning path will be up to a certain level.

1. What is class reflection?

1. the JAVA reflection mechanism is in the running state. For any class, all attributes and methods of the class can be known. For any object, it can call any of its methods and attributes. This dynamically obtained information and the function of dynamically calling methods of objects is called the reflection mechanism of Java.

2. Reflection is one of the features of the Java programming language. It allows the running Java program to check itself, also known as self-audit, and can directly operate on the internal properties of the program. For example, you can use it to obtain and display the names of members in the Java class.

3. This capability of Java is widely used in practical applications and does not exist in other programming languages. For example, Pascal, C, or C ++ cannot obtain information related to function definitions in the program.

4. JavaBean is one of the practical applications of class reflection. It allows some tools to operate software components visually. These tools use class reflection to dynamically load and obtain the attributes of Java components (classes. The various frameworks learned later will basically be reflected.

I first learned about class reflection. Next I will use an example to make it more visualized:

Value Object: Person

<span style="font-size:14px;">/** * @author xionghui * @date 2015-8-31 */public class Person {String name;int age;public Person(String name, int age) {super();this.name = name;this.age = age;}}</span>

Interface Class: api

<span style="font-size:14px;">/** * @author xionghui * @date 2015-8-31 */public interface USB {public abstract void work();}</span>
Implementation class: Usb1

<span style="font-size:14px;">import cn.hncu.xh.reflect.usb.api.USB;/** * @author xionghui * @date 2015-8-31 */public class Usb1 implements USB {@Overridepublic void work() {System.out.println("Usb1 is working...");}}</span>
Implementation class: Usb2

<span style="font-size:14px;">import cn.hncu.xh.reflect.usb.api.USB;/** * @author xionghui * @date 2015-8-31 */public class Usb2 implements USB {@Overridepublic void work() {System.out.println("Usb2 is Working...");}}</span>
Factory type: USBFactory

<Span style = "font-size: 14px;"> import java. io. fileInputStream; import java. util. properties; import cn. hncu. xh. reflect. usb. api. USB;/*** @ author xionghui * @ date 2015-8-31 */public class USBFcatory {public static USB getUSB () {try {// use the configuration file Properties p = new Properties (); FileInputStream fin = new FileInputStream ("usb. config "); p. load (fin); String name = p. getProperty ("name "). trim (); Class c = Class. forName (name); // class reflection return (USB) c. newInstance ();} catch (Exception e) {e. printStackTrace () ;}return null ;}</span>
Running class: Client

<Span style = "font-size: 14px;"> import cn. hncu. xh. reflect. vo. person;/*** @ author xionghui * @ date 2015-8-31 */public class ReflectGetClass {public static void main (String [] args) {getClassObj1 (); getClassObj2 (); getClassObj3 ();}/** get */private static void getClassObj3 () {Person p = new Person ("Jack", 25) through the getClass () method of the object ); class c = p. getClass (); System. out. println (c);}/** any data type (including basic data types) has a static attribute class, you can directly obtain the Class Object */private static void getClassObj2 () {Class c = Integer. class; System. out. println (c);}/** use Class. forName (String str) method to obtain the Class Object. This method depends on a String (Class name) and can be decoupled */private static void getClassObj1 () {try {Class c = Class. forName ("cn. hncu. xh. reflect. vo. person "); System. out. println (c);} catch (ClassNotFoundException e) {e. printStackTrace () ;}}</span>

Result:

If the configuration file usb. config:

Result:


If the configuration file usb. config:

Result:

2. Three Steps for reflection

Classes used for reflection, such as Method, can be found in the java. lang. reflect package. When using these classes, you must follow three steps:

Step 1: Obtain the java. lang. Class Object of the Class you want to operate on. In the running Java program, java. lang. Class is used to describe classes and interfaces.

Step 2: Call methods such as getDeclaredMethods to obtain a list of all methods defined in this class.

Step 3: Use the reflected API to perform such operations.

See the following code:

<span style="font-size:14px;">                         Class c = Class.forName("java.lang.String");                         Method ms[] = c.getDeclaredMethods();                         System.out.println(ms[0].toString());</span>
It prints the prototype of the first method defined in String in text format.

The following uses Class reflection to simulate the instanceof function: (call the isInstance method in the Class template)

Test class:

/*** @ Author xionghui * @ date 2015-8-31 * // test class public class A {int a = 10 ;}
Implementation class:

/*** @ Author xionghui * @ date 2015-8-31 */public class SimulateInstanceof {public static void main (String [] args) {System. out. println (isInstanceofA (new A (); System. out. println (isInstanceofA (new Integer (100);} private static boolean isInstanceofA (Object obj) {boolean boo = true; try {Class c = Class. forName ("cn. hncu. xh. reflect. instance. A "); // an exception is thrown here. The string is the path boo = c. isInstance (obj);} catch (ClassNotFoundException e) {e. printStackTrace () ;}return boo ;}}
Result:



3. Three Methods for getting Class objects

Method 1: Get the object using the getClass method. This method requires specific classes and objects of the class, and calls the getClass method.

Code:

/** Get */private static void getClassObj3 () {Person p = new Person ("Jack", 25); Class c = p. getClass (); System. out. println (c );}

Method 2: Any data type (including basic data types) has a static attribute class, which can be used to directly obtain the Class object corresponding to this type. In this way, you need to use a specific class, and then call the static Attribute class in the class. You do not need to call the method, and the performance is better.

Code:

/** Anyone's data type (including basic data types) has a static attribute class, which can be used to directly obtain the Class object of this type */private static void getClassObj2 () {Class c = Integer. class; System. out. println (c );}

Method 3: Use the Class. forName () method. In this way, you only need to use the Class name to obtain the Class Object of the Class, which is more conducive to extension.

Code:

/** Use Class. forName (String str) method to obtain the Class Object. This method depends on a String (Class name) and can be decoupled */private static void getClassObj1 () {try {Class c = Class. forName ("cn. hncu. xh. reflect. vo. person "); System. out. println (c);} catch (ClassNotFoundException e) {e. printStackTrace ();}}

Running class:

public static void main(String[] args) {getClassObj1();getClassObj2();getClassObj3();}
Result:


Iv. Anatomy of a class (retrieving class definition Information)

1. Obtain the class method: Find out the methods defined in a class, which is a very valuable and basic reflection usage.

2. Get the constructor of the class: Find the constructor defined in the class. The constructor does not return the type.

3. Get attribute fields of A Class: Find out which attribute fields are defined in a class.

5. Class calls (members in the call class)

1. Create an object using the constructor. Find the corresponding constructor Based on the specified parameter type, and pass in the corresponding parameter call for execution to create a new object instance.

2. Call method: Execute the method according to the method name. Based on the method name and parameter type matching the specified method, pass in the corresponding parameter and object for invocation. If it is a static method, you do not need to input a specific object.

3. Get and set attribute values: Read and modify attribute values based on the attribute name. to access non-static attributes, the object must be input as a parameter.

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.