"Java" "Reflection" __java

Source: Internet
Author: User
Tags reflection

The concept of a 1.Java reflection mechanism:

In the Java run-time environment, you can know which properties and methods of this class exist for any class. Can call any one of its methods for any object. The answer is yes. The ability to dynamically acquire the information of a class and the method of dynamically invoking an object comes from the reflection (Reflection) mechanism of the Java language.
Reflection is a key feature of Java as a dynamic (quasi dynamic) language. This mechanism allows the program to obtain internal information, including modifiers (such as static, public, and so on), superclass (for example, object) of any class with a known name through the reflection APIs at run time, Implements interfaces (such as Serializable), also includes all information for fields and methods, and can change fields content or Invoke methods at run time.

In general, the developer community, speaking of dynamic languages, generally agrees that a definition is: "When a program is run, it allows you to change the program structure or variable type, which is called a dynamic language." From this point of view, Perl, Python, Ruby are dynamic languages, C + +, Java, C # are not dynamic languages.

Although Java is not a dynamic language in this definition and classification, it has a very prominent dynamic correlation mechanism: Reflection. This word means "reflection, image, reflection," which is used in Java to refer to the classes that we can load, detect, and use during compilation. In other words, a Java program can load a class that knows its name at run time, learns its full structure (but does not include the definition of methods), generates its object entity, or sets a value on its fields, or evokes its methods. This ability to "See Through Class" (the ability of the program to examine itself) is called introspection (introspective, internal, introspective). Reflection and introspection are two terms that are often mentioned.


The 2.Java reflection mechanism mainly provides the following functions: (1) to determine the class to which any object belongs at runtime; (2) Constructing an object of any class at run time, (3) Determining the member variables and methods of any class at run time, and (4) the method of calling any object at run time.


3.Java Reflection APIs Introduction: In JDK, the Java reflection mechanism is implemented primarily by the following classes, which are located in the Java.lang.reflect package –class class: Representing a Class- Field class: A member variable that represents a class (a member variable is also a class property) –method class: A method that represents a class –constructor class: A constructor that represents a class –array class: Provides static methods for dynamically creating arrays and accessing elements of an array
In Java, these objects correspond to the same class object, regardless of how many objects are generated for a class.
Two example programs:

<span style= "Font-family:comic Sans ms;font-size:18px;" >import Java.lang.reflect.Method;

public class Dumpmethods {public
	
	static void Main (string[] args) throws exception{//class
		
		object describes a particular class object
		class<?> ClassType = Class.forName ("java.lang.String");
		
		Get all the methods through reflection
		method[] methods = Classtype.getdeclaredmethods ();
		
		Print all methods for
		(method M:methods) {
			System.out.println (m)}
	}}

</span>

<span style= "Font-family:comic Sans ms;font-size:18px;"

>import Java.lang.reflect.Method;
	public class Invoketester {public int add (int parm1, int parm2) {return parm1 + parm2;
	public string Echo (String message) {return ' Hello: ' + message;
		public static void Main (string[] args) throws Exception {//Invoketester test = new Invoketester ();
		System.out.println (Test.add (1, 2));
		
		System.out.println (Test.echo ("Java"));
		
		class<?> ClassType = Invoketester.class;
		
		Generates an object of type Invoketester () by Reflection (Classtype.newinstance);
		
		Get to add method by Reflection Addmethod = Classtype.getmethod ("Add", new class[] {int.class, int.class});
		
		Invokes the Add method of the object and passes the arguments in System.out.println (Addmethod.invoke (O,new object[]{1,2}));
		
		Gets the Echo method by Reflection Echomethod = Classtype.getmethod ("echo", New Class[]{string.class});
	Invokes the Echo method of the object and passes the arguments in System.out.println (Echomethod.invoke (o, New object[]{"Java"}); }}</span>

To use reflection, you first need to get the class object that you want to work on or object.
Gets 3 ways of the class object corresponding to the classes or objects: 1 uses the static method of the class class forname, such as Class.forName ("java.lang.String"); 2 use. Class syntax, such as String.class; 3 Use the GetClass method of the object, such as String s = "abc"; class<?> ClassType = S.getclass ();
If you want to build the object by using the constructor of the class without parameters, we have two ways: 1 to get the class object and then get it directly from the class object's Newinstance method.  such as class<?> ClassType = String.class; Object o = classtype.newinstance (); 2 first obtains the class object, then obtains the corresponding constructor object through this class object, then builds through the constructor object's Newinstance method. such as class<?> ClassType = Customer.class; Constructor constructor =classtype.getconstructor (new class[]{}); Object O1 = constructor.newinstance (New object[]{});
If you want to build an object from a class with a parameter-structured method, you can only use this method: class<?> ClassType = Customer.class;
Constructor Constructor2 = Classtype.getconstructor (New Class[]{string.class,int.class});
Object O2 = constructor.newinstance (New object[]{"John", 20});

A slightly complete example:
<span style= "Font-family:comic Sans ms;font-size:18px;"
>import Java.lang.reflect.Field;

Import Java.lang.reflect.Method; public class Reflecttest {//This method implements a copy of the customer public static object (object) throws Exception {class<

		?> ClassType = Object.getclass ();

		Object objectcopy = Classtype.getconstructor (new class[] {}). newinstance (New object[] {});

		field[] fields = Classtype.getdeclaredfields ();
			for (Field field:fields) {String name = Field.getname (); String firstletter = name.substring (0, 1). toUpperCase ()//convert the first letter of the property to an uppercase String Getmethodname = "Get" + Firstletter + N
			Ame.substring (1);

			String setmethodname = "Set" + Firstletter + name.substring (1);
			Method GetMethod = Classtype.getmethod (Getmethodname, new class[] {});

			Method Setmethod = Classtype.getmethod (Setmethodname, new class[] {field.gettype ()});

			Object value = Getmethod.invoke (object, new object[] {}); Setmethod.invoke (Objectcopy, new object[] {VAlue});
	return objectcopy;
		public static void Main (string[] args) throws Exception {Customer c = new Customer ("Tom", 20);
		C.setid (1L);
		Object o = copy (c);

		Customer customercopy = (customer) O;

	System.out.println (Customercopy.getid () + "," + customercopy.getname () + "," + customercopy.getage ());
	Class Customer {private long ID;
	private String name;

	private int age;
		Public customer () {} ' public customer ' (String name, int age) {this.name = name;
	This.age = age;
	Public long GetId () {return id;
	public void SetId (long id) {this.id = ID;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	public int getage () {return age;
	public void Setage (int age) {this.age = age; }}</span>

The Java.lang.Array class provides a variety of static methods for dynamically creating and accessing array elements. First example:
<span style= "Font-family:comic Sans ms;font-size:18px;" >import Java.lang.reflect.Array;

public class Arraytester {public
	
	static void Main (string[] args) {
		
		class<?> ClassType = string.class;
		
		Object array = array.newinstance (ClassType);
		
		Array.set (Array, 5, "Hello");
		
		string s = (string) array.get (Array, 5);
		
		System.out.println (s);
	}
</span>

Second example: Integer.type returns the class object corresponding to int
Integer.class returns the class object corresponding to the integer
<span style= "Font-family:comic Sans ms;font-size:18px;" >import Java.lang.reflect.Array;

public class ArrayTester2 {public
	
	static void Main (string[] args) {
		
		int[] dims = new int[]{5,10,15};
		
		Object array = array.newinstance (Integer.type, dims);
		
		Object arrayobj = Array.get (Array, 3);		class<?> ClassType = Arrayobj.getclass (). Getcomponenttype ();		
//		System.out.println (ClassType);
		
		Arrayobj = Array.get (arrayobj, 5);
		
		Array.set (Arrayobj, Panax Notoginseng);
		
		Int[][][] Arraycast = (int[][][]) array;
		
		System.out.println (arraycast[3][5][10]);
		
	}
</span>


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.