Java reflection mechanism in-depth explanation, java reflection explanation

Source: Internet
Author: User

Java reflection mechanism in-depth explanation, java reflection explanation
1. Concepts

Reflection maps various Java components into corresponding Java classes.

The Class construction method is private, which is created by JVM.

Reflection is a feature of the java language. It allows the program to perform self-check and perform operations on internal members at runtime (not during compilation. For example, it allows a java class to obtain and display all its member variables and methods. This capability of Java may not be used in many practical applications, but it does not exist in other programming languages. For example, Pascal, C, or C ++ cannot obtain information related to function definitions in the program. (From Sun)

JavaBean is one of the practical applications of reflection. It allows some tools to operate software components visually. These tools dynamically load and obtain the attributes of Java components (classes) through reflection.

Reflection exists from 1.2, and all the later three frameworks will use the reflection mechanism, which involves the Class "CLass" and cannot directly use new Class (). Its object is a bytecode in the memory.

An instance of the Class indicates the classes and interfaces in the running Java application. Enumeration is a type, and annotation is an interface. Each array is a Class mapped to a Class Object. All arrays with the same element type and dimension share the Class object. Basic Java types (boolean, byte, char, short, int, long, float, and double) and keywords void are also represented as Class objects. Class does not have a public constructor. The Class object is automatically constructed by the Java Virtual Machine during Class loading and by calling the defineClass method in the Class loader.

1 Person p1 = new Person ();
2 // The following three methods can obtain bytecode
3 CLass c1 = Date. class ();
4 p1.getClass (); 5 // if the class exists, it is loaded. Otherwise, a new class is often created. The class name is not required when writing the source program. It is passed to the running class.
6 Class. forName ("java. lang. String ");

CLass. the forName () bytecode has been loaded into the Java Virtual Machine to obtain the bytecode. the Java Virtual Machine has not yet generated the bytecode to load with the class loader, And the loaded bytecode is buffered into the virtual machine.

The following simple example shows how reflection works.

 

Import java. lang. reflect .*;


Public class DumpMethods {

Public static void main (String args []) {

Try {

Class c = Class. forName ("java. util. Stack ");


Method m [] = c. getDeclaredMethods ();

For (int I = 0; I <m. length; I ++)

System. out. println (m [I]. toString ());

}

Catch (Throwable e ){

System. err. println (e );

}

}

}

 

1 public synchronized java.lang.Object java.util.Stack.pop() 2 public java.lang.Object java.util.Stack.push(java.lang.Object) 3 public boolean java.util.Stack.empty() 4 public synchronized java.lang.Object java.util.Stack.peek() 5 public synchronized int java.util.Stack.search(java.lang.Object)

In this way, the names of java. util. Stack classes and their delimiters and return types are listed. This program uses Class. forName to load the specified Class, and then calls getDeclaredMethods to obtain the list of methods defined in this Class. Java. lang. reflect. Methods is a class used to describe a single method in a class.

The following example uses a Class object to display the Class name of an object:

1 void printClassName(Object obj) {
2          System.out.println("The class of " + obj +
3                             " is " + obj.getClass().getName());
4      }

You can also use a Class literal value (JLS Section 15.8.2) to obtain Class objects of the specified type (or void. For example:

1 System.out.println("The name of class Foo is: "+Foo.class.getName());

When there is no object instance, there are two main methods.

 

// Two methods for obtaining the class type

Class cls1 = Role. class;

Class cls2 = Class. forName ("yui. Role ");

Note that in the second method, the forName parameter must be a complete Class Name (package name + class name), and this method needs to capture exceptions. Now cls1 can be used to create an instance of the Role Class. The newInstance method of the Class is equivalent to the default constructor of the calling Class.

1 Object o = cls1.newInstance (); 2 // create an instance
3 // Object o1 = new Role (); // equivalent to the above method

Ii. Common Methods

1. isPrimitive (determine whether it is a basic type of bytecode)

 

Public class TestReflect {

Public static void main (String [] args ){

// TODO Auto-generated method stub

String str = "abc ";

Class cls1 = str. getClass ();

Class cls2 = String. class;

Class cls3 = null; // null must be added

Try {

Cls3 = Class. forName ("java. lang. String ");

} Catch (ClassNotFoundException e ){

// TODO Auto-generated catch block

E. printStackTrace ();

}

System. out. println (cls1 = cls2 );

System. out. println (cls1 = cls3 );

System. out. println (cls1.isPrimitive ());

System. out. println (int. class. isPrimitive (); // determines whether the specified Class object represents a basic type.

System. out. println (int. class = Integer. class );

System. out. println (int. class = Integer. TYPE );

System. out. println (int []. class. isPrimitive ());

System. out. println (int []. class. isArray ());

}

}

/*

* True

True

False

True

False

True

False

True


*/

*/

2. getConstructor and getConstructors ()

In java, constructor methods are not sequenced by the type and number of parameters.

 

Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException {

// TODO Auto-generated method stub

String str = "abc ";

System. out. println (String. class. getConstructor (StringBuffer. class ));

}

}

3. The Filed class represents a member variable in a certain category.

 

Import java. lang. reflect. Field;

Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {

ReflectPointer rp1 = new ReflectPointer (3, 4 );

Field fieldx = rp1.getClass (). getField ("x"); // It must be x or y

System. out. println (fieldx. get (rp1 ));

/*

* The private member variables must use getDeclaredField and setAccessible (true). Otherwise, the private member variables cannot be obtained.

*/

Field fieldy = rp1.getClass (). getDeclaredField ("y ");

Fieldy. setAccessible (true); // brute force reflection

System. out. println (fieldy. get (rp1 ));

}

}


Class ReflectPointer {

Public int x = 0;

Private int y = 0;

Public ReflectPointer (int x, int y) {// alt + shift + s is equivalent to right-clicking source

Super ();

// TODO Auto-generated constructor stub

This. x = x;

This. y = y;

}

}

Iii. Typical examples

1. Change B in all String member variables to.

 

Import java. lang. reflect. Field;

Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {

ReflectPointer rp1 = new ReflectPointer (3, 4 );

ChangeBtoA (rp1 );

System. out. println (rp1 );

}

Private static void changeBtoA (Object obj) throws RuntimeException, Exception {

Field [] fields = obj. getClass (). getFields ();

For (Field field: fields ){

// If (field. getType (). equals (String. class ))

// The equals semantics is inaccurate because only one bytecode is available.

If (field. getType () = String. class ){

String oldValue = (String) field. get (obj );

String newValue = oldValue. replace ('B', 'A ');

Field. set (obj, newValue );

}

}

}

}


Class ReflectPointer {

Private int x = 0;

Public int y = 0;

Public String str1 = "ball ";

Public String str2 = "basketball ";

Public String str3 = "itcat ";

Public ReflectPointer (int x, int y) {// alt + shift + s is equivalent to right-clicking source

Super ();

// TODO Auto-generated constructor stub

This. x = x;

This. y = y;

}


@ Override

Public String toString (){

Return "ReflectPointer [str1 =" + str1 + ", str2 =" + str2 + ", str3 ="

+ Str3 + "]";

}

}

2. Write a program to call the main method in the class based on the class name provided by the user.

Why is reflection required?

 

Import java. lang. reflect. Field;

Import java. lang. reflect. Method;


Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {

String str = args [0];

/*

* In this way, the array badge is out of the range, because there is no such character array.

* You need to right-click run as-statements ations-arguments and enter B. Inter (complete class name)

*

*/

Method m = Class. forName (str). getMethod ("main", String []. class );

// Either of the following methods is acceptable. The main method requires a parameter

M. invoke (null, new Object [] {new String [] {"111", "222", "333 "}});

M. invoke (null, (Object) new String [] {"111", "222", "333"}); // The array is also an Object.

/*

* M. invoke (null, new String [] {"111", "222", "333 "})

* None of the above, Because java will automatically split the package

*/

}

}


Class Inter {

Public static void main (String [] args ){

For (Object obj: args ){

System. out. println (obj );

}

}

}

3. Simulate the instanceof Operator

 

Class S {

}


Public class IsInstance {

Public static void main (String args []) {

Try {

Class cls = Class. forName ("S ");

Boolean b1 = cls. isInstance (new Integer (37 ));

System. out. println (b1 );

Boolean b2 = cls. isInstance (new S ());

System. out. println (b2 );

}

Catch (Throwable e ){

System. err. println (e );

}

}

}

In this example, a Class Object of the S Class is created, and then check whether some objects are S instances. Integer (37) is not, but new S () is.

Iv. Method class

Represents a method in a class (not an object.

 

Import java. lang. reflect. Field;

Import java. lang. reflect. Method;

/*

* A person draws a circle on the blackboard, involving three objects. The circle needs the center and radius, but is private.

* It is not suitable to assign to users.

*

* The driver only sends a command to the train to step on the brakes. The brake operation must be completed by the train.

*

* The interview often involves object-oriented design. For example, when people close their doors, they simply push the door.

*

* This is the expert mode: The method is assigned to anyone who owns the data and who is the expert.

*/

Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {

String str = "shfsfs ";

// The package starts with com, which indicates sun is used internally, and java is used as the user's header.

Method mtCharAt = String. class. getMethod ("charAt", int. class );

Object ch = mtCharAt. invoke (str, 1); // if the first parameter is null, it must be a static method.

System. out. println (ch );

System. out. println (mtCharAt. invoke (str, new Object [] {2}); // 1.4 syntax

}

}

5. array reflection

The Array tool class is used to perform Array reflection.

The same type and latitude have the same bytecode.

Int. class and Integer. class are not the same bytecode. Integer. TYPE indicates the bytecode of the basic class corresponding to the packaging class. int. class = Integer. TYPE

 

Import java. util. Arrays;


/*

* From this example, we can see that even if the bytecode is the same but the object is not necessarily the same, it is not the same thing at all.

*

*/

Public class TestReflect {

Public static void main (String [] args) throws SecurityException, NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, Exception {

Int [] a = new int [3];

Int [] B = new int [] {, 5}; // The length cannot be specified after direct assignment; otherwise, CE

Int [] [] c = new int [3] [2];

String [] d = new String [] {"jjj", "kkkk "};

System. out. println (a = B); // false

System. out. println (a. getClass () = B. getClass (); // true

// System. out. println (a. getClass () = d. getClass (); // compare bytecode a and cd.

System. out. println (a. getClass (); // output class [I

System. out. println (a. getClass (). getName (); // output [I, brackets representing arrays, And I representing Integers

System. out. println (a. getClass (). getSuperclass (); // output class java. lang. Object

System. out. println (d. getClass (). getSuperclass (); // output class java. lang. Object

// Because all the parent classes are objects, the following operations are acceptable.

Object obj1 = a; // not an Object []

Object obj2 = B;

Object [] obj3 = c; // an array of the basic type can only be used as an Object, and must be used as an Object []

Object obj4 = d;

// Note the difference between asList processing int [] and String []

System. out. println (Arrays. asList (B); // 1.4 No variable parameter. The array is used, [[I @ 1bc4459]

System. out. println (Arrays. asList (d); // [jjj, kkkk]

}

}

Vi. Conclusion

The above is the simple use of the reflection mechanism. Obviously, those who have learned spring understand why we can get the specified methods and variables through the configuration file, when we create an Object, it is implemented by passing it into the string, as if you need something, we will produce it for you, and we have been using the Object, which shows the dynamic characteristics of the java language, the dependency is greatly reduced.

If you have any questions during Java learning or want to obtain learning resources, you are welcome to join the Java learning exchange QQ Group of the LEADER: 618528494.

Chat is prohibited in the group. The number of places is limited.

  • Http://www.cnblogs.com/hxsyl/archive/2013/03/23/2977593.html

Head of Java

No.: javatuanzhang

Sharing Java technical expertise on a daily basis

Long-pressed QR code recognition

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.