Deep Java Reflection

Source: Internet
Author: User

Reflection of the Cornerstone--class class
Java classes in Java programs belong to the same kind of things, the Java class name describing such things is class. For example: Many people can use a person class to express, and this class can describe the human information (name, age, gender, etc.), and many Java classes can be expressed in class.
The Question:person class represents a person whose instance object can be John, Dick, and class classes that represent Java classes, and what each instance object represents.
Answer: Corresponds to the byte code of each class in memory. A class is loaded into memory by the class loader, occupy a storage space, the contents of this space is the byte code of the class, different classes of the byte code is different, so they in the contents of the memory is different, this space can be used to represent each object, these objects obviously have the same type, That is the class type.

There are three ways to get instance objects corresponding to each byte code:
1, class name. Class, for example: System.class
2. Object. GetClass (), for example: New Data (). GetClass ()
3, Class.forName ("Class name"), for example: Class.forName ("Java.util.Date")

Class class properties and methods see JDK

Reflection
Reflection is the mapping of various components in a Java class to the corresponding Java class. For example, a Java class is represented by an object in a class class, which is represented by one of the classes: member variables, methods, construction methods, packages, and so on. Class classes that represent Java classes clearly provide a series of methods for obtaining variables, methods, constructs, modifiers, packages, and so on, which are represented by instance objects of the corresponding class, which are field, method, Contructor, package, and so on.

Contructor class
1, to get a class of all the construction methods:
contructor[] Contructors = Lass.forname ("class name"). Getcontructors ();
2, to get a specific construction method:
Type used when getting methods
Contructor contructors = Class.forName ("class name"). Getcontructor (parameter type. class,...);
3. Create Instance Objects
Usual way: String str = new string (New StringBuffer ("abc"));
When you call the method you get, you use an instance of the same type above
Reflection mode: String str = (string) contructor.newinstance (new StringBuffer ("abc"));
4, Class.forName ();
• Example: String obj = (string) class.forname ("java.lang.String"). Newinstence ();
• The method internally gets the default construction method, and then creates an instance with the constructed method
• What is the internal specific code for the method? object using caching mechanism to save default constructor method

Field Class
The filed class represents a member variable in a class
Example:
Refletpoint.java
private int x;

public int y;

Public Reflectpoint () {}

Public reflectpoint (int x,int y) {
this.x = x;
This.y = y;
}

Fieldtest.java
Reflectpoint P1 = new Reflectpoint (2,8);
Field fy = class.forname ("Com.zouc.reflect.ReflectPoint"). GetField ("Y");
System.out.println (Fy.get (p1)); 8

Field FX = Class.forName ("Com.zouc.reflect.ReflectPoint"). Getdeclaredfield ("X");
Fx.setaccessible (TRUE);
System.out.println (Fx.get (p1)); 2

Question: The resulting Field object is a member variable that corresponds to a class. Or an idiom variable that corresponds to an object.
Anwser: is a member variable on a class. Because the object can have multiple, and the class has only one, so Fx.fy is the byte code on the resulting class.

Method class
The method class represents one of the member methods in a class
• Get a method in a class
Example: Method charAt = Class.forName ("java.lang.String"). GetMethod ("CharAt", Int.class);
• Calling Method:
Usual Way: Str.charat (1);
Reflection mode: Charat.invoke (str,1);
Note: If the first argument to the Invoke () method passed to the methods object is null, this means that the method object corresponds to a static
Example: Reflection on a member method that receives an array parameter
Package com.zouc.reflect;

Import java.lang.reflect.InvocationTargetException;
Import Java.lang.reflect.Method;

public class Test {

public static void Main (string[] args) throws SecurityException, Nosuchmethodexception, CLASSNOTFOUNDEXCEP tion, illegalargumentexception, illegalaccessexception, invocationtargetexception {
String startingclassname = args[0];
Method Mainmethod = Class.forName (startingclassname). GetMethod ("main", String[].class);
Mainmethod.invoke (null, (Object) New string[]{"abc", "Def", "XYZ"});
}

}

Class Argumenmts {
public static void Main (string[] args) {
for (String Arg:args) {
System.out.println (ARG);
}
}
}

reflection of an array
• Arrays with the same dimensions and element types are of the same type, that is, they have the same class instance object
• The parent class for the Getsuperclass () method that represents the class instance object of an array is the class that corresponds to the object class
• One-dimensional arrays of basic types can be used as ojbect types and cannot be used as object[] types, and two-dimensional arrays can be used as object types or as object[] types
Example:
Int[] A = new int[3];
Int[] B = new Int[4];
Int[][] C = new Int[3][4];
String[] s = new string[5];

System.out.println (a.getclass () = = B.getclass ()); True
System.out.println (a.getclass () = = C.getclass ()); False
System.out.println (c.getclass () = = S.getclass ()); False
· The array tool class is used to complete reflection operations on arrays
public static void PrintObject (Object obj) {
Class obyte = Obj.getclass ();
if (Obyte.isarray ()) {
int len = array.getlength (obj);
for (int i = 0; i < len; i++) {
System.out.println (Array.get (obj, i));
}
} else {
System.out.println (obj);
}
         }

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.