Dark Horse Programmer----A summary of the reflection learning of Java high technology

Source: Internet
Author: User
Tags access properties throw exception

-------Android Training, Java training, look forward to communicating with you! ----------

The concept of 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 method of the object is called the reflection mechanism of the Java language.

The subtle summary is that reflection is the mapping of the various components in the Java class into the corresponding Java classes.

3, in Java, the various classes describing things are also a thing, can also be described by the object-oriented approach, that is, there is also a class to describe a large number of Java classes.

4, reflection is also known as the anatomy of the class. For example, a class has member variables, construction methods, member methods, packages and other information, through reflection, you can get the various information of this class.

5, using the reflection mechanism of Java, generally need to follow three steps:
Get the class object you want to manipulate
The class object obtained by the first step gets the method or property name of the operation
The method or property copy code obtained in the second step of the operation

Class--the basis of reflection

All of the class files in Java have some of the same characteristics that are extracted upward, encapsulating the generic content into a new class, which is the object that describes the bytecode file.

Class description Information: The name of the classes, the access properties of the class, the package name to which the class belongs, the list of field names, the list of method names, etc.

Each byte code is an instance object of class.

Get the Class object method
1. Through the static properties of all data types. class to get

Class name. class Example: String.class

2, through the object's GetClass () method to obtain

Object. GetClass () For example: New String ("123"). GetClass ();

3, through the class class static method Forname () and to get the class name of a class object to get

Class.forName (package name. class name); For example: Class.forName ("java.lang.String");

Method Example:

public class classtest{
public static void Main (String[]args) throws exception{
String str = "123456";
Class CLS1 =string.class;
Class cls2 = Str.getclass ();
Class CLS3 = Class.forName ("java.lang.String");
System.out.println (cls1 = = CLS2);//true
System.out.println (cls2 = = CLS3);//true
}
}

The above example also shows that there is only one copy of the bytecode file in the same class. is the same class instance object.

Nine pre-defined instance objects in Java:

Basic data types (Byte, Boolean, short, int, long, double, float, char) bytecode objects and a void.class with a return value of type void

Integer.type is a constant of the integer class that represents the byte code of the base type wrapped by this wrapper type, which is the byte code of type int, so it is equal to Int.class.

In addition, arrays with the same data types and dimensions are mapped to the same class object in Java. Determine if it is an array type, using Class.isarray ().

Common methods in class classes

1) forname (string className) returns the class object that is associated with the given string name of the classes or interfaces.

2) GetClass () returns the Object runtime class, which returns the class object as a byte-code object

3) GetConstructor () returns the constructor object, which reflects the specified public constructor method for the class represented by this class object.

4) GetField (String name) returns a Field object that represents the class or interface for the specified public member fields.

5) GetFields () returns an array containing some field objects representing the member fields in the represented class.

6) GetMethod (String name,class ... parametertypes) returns a Method object that represents the specified public member methods for the class represented by this class object.

7) Getmehtods () returns an array containing some method objects, which is a public member method in the class that is represented.

8) string GetName () returns the entity name represented by this class object in string form.

9) String Getsuperclass () returns the name of the superclass of the class represented by this class

Boolean IsArray () determines whether this class object represents an array

One) Boolean isprimitive () determines whether the specified class object is a basic type.

Newinstance () Creates a new instance of the class represented by this class object. Note: This method initializes the instance object with the empty parameter constructor.

 
constructor class ... .. (reflection of the construction method)

1. The instance object of constructor represents a method of constructing a class.

2, get the construction method:

Gets all the constructor methods in a class

Constructor[] Con=class.forname ("java.lang.String"). GetConstructors ();

Get one of the constructor methods in a class

Constructor Con=string.class.getconstructor (Stringbuffer.class);

3. Comparison between creating an instance object and reflection creation

General mode: String s = "123";

Take advantage of Reflection: string s = (string) constructor.newinstance ("123");//You can specify which constructor to use to create.

Precautions:

1. When you create an instance, the argument list in the Newinstance method must match the parameter list in the method GetConstructor methods that get constructor.

2. newinstance (): Constructs an instance object that constructs an object each time it is called.

3. The advantage of using the constructor class to create a class instance is that you can specify a constructor, and the class class can only use the parameterless constructor to create an instance object.

Code instance

Package day24;

Import Java.lang.reflect.Constructor;

public class Consdemo

{

public static void Main (String [] args) throws Exception

{

Class cl =class.forname ("java.lang.String");//Gets the class object for sring classes.

Constructor con =cl.getconstructor (stringbuffer.class);//Gets the construction method of the class object of the String class

String st= (String) constructor.newinstance (new StringBuffer ("practice of constructor creating instance objects")

}

}

Field class ..... (Reflection of member variables)

1. Represents a member variable in a class in reflection

2. Common methods:

1) Field GetField (String s);//access to public and parent classes only

2) Field Getdeclaredfield (String s);//gets any member variable in the class, including the private

3) setaccessible (ture);//If it is a private field, you first have the ability to remove the permission check for that private field. Also known as violent visits.

4) Set (object obj, object value);//sets the field represented by the specified object variable to the specified new value.

5) object get (object obj);//Returns the value of the field represented on the specified object.


Method class ..... (Reflection of Member methods)

1. Represents a member method in a class.

2, the common method

1) Method [] GetMethods (); Get all methods in the public and parent classes only

2) Method [] getdeclaredmethods (); Gets the methods in this class that contain private methods

3) method [] GetMethod ("Method name", parameter. Class (null argument can write null));

4) object invoke (object obj, parameter); Call method: If the method is static, the argument in invoke can be written to null

3. Call method

Get a method in the class: Sting str= "123";

Method Mcharat = Class.forName ("java.lang.String"). GetMethod ("CharAt", Int.class);

Call Method:

General mode: Str.mcharat (2);

Reflection mode: Mcharat.invoke (str,2)

If the first parameter of the Invoke () method passed to the method object is null, the method object corresponds to a static method.

4. The difference between the Invoke method of JDK1.4 and JDK1.5:

Jdk1.4:public object Invoke (Object obj,object[] args)

Jdk1.5:public object Invoke (Object Obj,object ... args)

By JDK1.4 syntax, you need to pass an array as an argument to the Invoke method when it takes an array as an element. At this point, if we are going to take out the elements, we need to take the elements of the array out through the array.

Therefore, the code that calls the Mcharat method can also be rewritten in JDK 1.4 as Charat.invoke ("str", New Object[]{1}).

code example:

Import java.lang.reflect.*;

Import java.util.*;

Class Invok

{

public static void Main (string[] args) throw Exception

{

String s = "123";

Method Mcharat=string.class.getmethod ("CharAt", Int.class);

System.out.println (Mcharat.invoke (s,1); 1.5 of the wording

System.out.println (Mcharat.invoke (S,new object[]{1})); 1.4 of the wording

}

}

The Member method that receives the array parameter is reflected.

Requirement: Use the Reflection method to run the main function of a class

code example:

Package Com.ithema.day1

Import java.lang.reflect.*;

Import util.*;

public class Mainmethod

{

public static void Main (string[] args) throw exception{

Class cl=class.forname ("Com.itheima.day1.Test"); It is entirely possible to use a variable to represent the class name, such as

Method Me=cl.getmethod ("main", String[].class); This can reflect the role of reflection, when it is not clear that the class name only

Me.invoke (null,new string[]{"AA", "BB", "CC"}) variables are still running with reflection the main function of the class can be

}

}

Class Test

{

public static void Main (string[] args)

{

for (String S:args)

{System.out.println (s);}

}

}

This code will take exception: illegal parameter exception

The parameter of the main method in the Java program is enabled is an array of strings. Invoke the Main method by reflection, invoke how to pass arguments: An array in JDK1.5 is a parameter, 1.4 is an array of each element is a parameter, 1.5 is compatible with 1.4, so the delivery time will be passed by 1.4 method. So the red flag part is wrong.

Workaround:

1.me.invoke (Null,new object[] (new string[]{"11", "22", "33"});

2.me.invoke (null, (Object) New string[]{"11", "22", "33"}); The compiler does special processing and does not treat parameters as arrays

Reflection of an array

1. Arrays of the same type and dimension are of the same type, that is, have the same class instance object.

2, the byte code file name of the array is [the first letter of the array type uppercase, such as: int[] for [I;

3. The Getsuperclass () of the instance object of the array corresponding to class returns the class object of the parent class object class.

4, a one-dimensional array of the basic type can be used as object type, not as object[] type, non-primitive type of one-dimensional array, can be used as object type, and can be used as the object[] type.

5, Arrays.aslist () method to deal with int[] and string[] difference: 1.4 and 1.5 new characteristics difference. 1.4 Cannot process int array, return to 1, 5 processing, 1.5 treat int array as one parameter

6. Array Reflection: The array tool class is used to complete the operation of array reflection.

Array.getlength (Object obj);//Get array length

Array.get (Object obj,int x);//Gets the elements in the array

7. How to get the type of an element in an array,

Example: int a = new int[3];object[] obj=new object[]{"ABC", 1};

Cannot get the specific type of an array, only the type of one of the elements.

such as: Obj[0].getclass (). GetName () got the java.lang.String

The effect of reflection

Core issues to be solved by framework and framework
I do the house to sell to the user, the user installs the windows and doors and the air conditioning, I do the house is the framework, the user needs to use my frame, the windows and doors into the framework I provide. The framework differs from the tool class, where the tool class is called by the user's class, while the framework invokes the user-supplied class.
Core issues to be addressed by the framework
When I write the framework, you may still be in primary school, and you will not be able to write programs yet. How does the framework program I write call the class you write later (Windows and doors)?
Because there is no way to know the class name to be called when writing a program, you cannot directly new the instance object of a class in your program, but instead use reflection.

This article is from the "Dot Drop" blog, please be sure to keep this source http://arctictern.blog.51cto.com/10120640/1662452

Dark Horse Programmer----A summary of the reflection learning of Java high technology

Related Article

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.