Class reflection
class reflection, this is a Java advanced technology, if you learn this, then your Java learning path on a step.
First, what is class reflection?
1, the Java 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 object's methods are called the reflection mechanisms of the Java language.
2, Reflection (Reflection) is one of the characteristics of Java programming language, it allows the running Java program to check itself, also known as self-audit, and can directly manipulate the internal properties of the program. For example, you can use it to get the names of the members in the Java class and display them.
3, Java This ability in the practical application of many, in other programming languages there is no such a sacrifice. For example, there is no way to get information about a function definition in a program in Pascal, C, or C + +.
4, JavaBean is one of the practical applications of class reflection, it can make some tools to visualize the operation of software components. These tools dynamically load and take the properties of a Java component (class) through class reflection. The various frameworks behind the study will basically have reflective use.
A preliminary understanding of class reflection, followed by an example to make him more figurative:
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. {super (); this.name = Name;this.age = Age;}} </span>
Interface classes: 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 {@Ov erridepublic 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 {@Ov erridepublic void Work () {System.out.println ("USB2 is working ...");}} </span>
Factory class: 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 config 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>
Run class: Client
<span style= "FONT-SIZE:14PX;" >import cn.hncu.xh.reflect.vo.person;/** * @author Xionghui * @date 2015-8-31 */public class Reflectgetclass {public St atic void Main (string[] args) {getClassObj1 (); GetClassObj2 (); GetClassObj3 ();} /* * gets */private static void GetClassObj3 () {person p=new person ("Jack", 25) through the object's GetClass () method; Class C=p.getclass (); System.out.println (c);} /* * Anyone data type (including base data type) has a static attribute class, which allows you to directly get the class object of that type */private static void GetClassObj2 () {class C=integer.class ; System.out.println (c);} /* * Gets the class object by Class.forName (String str), which relies on the string (the name of the class) 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>
Results:
If the configuration file Usb.config:
Results:
If the configuration file usb.config:
Results:
Ii. Three steps for reflection use
Classes for reflection, such as method, can be found in the Java.lang.reflect package. There are three steps to follow when using these classes:
The first step: Get the Java.lang.Class object of the class you want to manipulate. In a running Java program, use the Java.lang.Class class to describe classes and interfaces, and so on.
Step Two: Call a method such as Getdeclaredmethods to get a list of all the methods defined in the class.
Step Three: Use the reflected API to manipulate this information.
As in 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 will print the prototype of the first method defined in string as text.
The following uses class reflection to simulate the functionality of instanceof: (is to call the Isinstance method in the class template)
Test class:
/** * @author Xionghui * @date 2015-8-31 *///Test 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 "); This throws an exception, the string is the path to your file boo=c.isinstance (obj);} catch (ClassNotFoundException e) {e.printstacktrace ();} return boo;}}
Results:
Iii. three ways to get class objects
Method One: Obtained by means of getclass of the object. This approach requires specific classes and objects of that class, as well as calling the GetClass method.
Code:
/* * gets */private static void GetClassObj3 () {person p=new person ("Jack", 25) through the object's GetClass () method; Class C=p.getclass (); System.out.println (c);}
Mode two: Any data type (including basic data types) has a static attribute class, which allows you to get directly to the class object of that type. This is done in a way that uses a specific class and then calls the static property class in the class, without calling the method and performing better.
Code:
/* * Anyone data type (including base data type) has a static attribute class, which allows you to directly get the class object of that type */private static void GetClassObj2 () {class C=integer.class ; System.out.println (c);}
Method Three: obtained by Class.forName () method. In this way, you can get the class object of the classes only by using the class name, which is more advantageous for the extension.
Code:
/* * Gets the class object by Class.forName (String str), which relies on the string (the name of the class) 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 ();}}
Run the class:
public static void Main (string[] args) {getClassObj1 (); GetClassObj2 (); GetClassObj3 ();}
Results:
Iv. Anatomy of a class (get definition information for a class)
1, get the method of the class: Find out what method is defined in a class, this is a very valuable and very basic reflection usage.
2. Gets the constructor for the class: finds the constructor defined in a class, and the constructor does not have a return type.
3. Get the attribute fields for the class: Find out which attribute fields are defined in a class.
V. Invocation of a class (calls to members in a class)
1. Constructs a class object using the constructor to create a new object. Finds the appropriate constructor based on the specified parameter type, passing in the corresponding parameter call execution to create a new object instance.
2. Call method: Executes the method based on the method name. The specified method is matched against the parameter type according to the method name, and the corresponding parameter is passed in with the object to invoke execution. In the case of static methods, no specific objects need to be passed in.
3. Get and Set property values: The value of the property is read and modified according to the property name, and accessing the non-static property requires passing in the object as a parameter.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Advanced Value class reflection