On the reflection mechanism of Java

Source: Internet
Author: User

I. A brief discussion on the reflection mechanism of Java

The recent study of Java research has been very strong, mainly to see the blog as a learning style. Here are some of my reflections on the reflection mechanism of Java, I hope you can see the mistakes of children shoes to point out. Subject to your advice, if you let the niche well moved, you might be invited to dinner Oh!

1. What is a reflection mechanism?

Based on the web, the reflection mechanism in Java can be defined like this:

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; This dynamically acquired information and the ability to dynamically invoke the method of the object is called the reflection mechanism of the Java language.

2. How the reflection mechanism is implemented

When it comes to reflection, the most tempting thing is the word "dynamic". Children who have been exposed to the C language know that there is also a function of "dynamic" catching edge in C: malloc () function. In fact, the two dynamic here is a meaning, refers to the non-compile-time processing, or run-time processing. This mechanism can add a lot to the flexibility of the program, because by this mechanism, the client can change some of the nature of his concerns while the program is running: allocating memory (he probably doesn't know it at all), calling a class (of course he's still in the dark).

Let's talk about how the dynamic mechanism in Java is implemented.

The previous article mentions the loading of Java classes, but does not have a deeper explanation of how it works, so let's talk about this in the first place.

The first thing you have to mention is the Java.lang.Class class.

There is such a passage:

Java programs run at runtime and the Java Runtime system always identifies all objects as run-time types. This information records the classes each object belongs to. A virtual machine typically uses run-time type information to perform the correct method, and the class that holds the type information is the classes class.

That is, ClassLoader found the class that needs to be called (Java in order to regulate the memory of the call consumption, the load of the class will be done when needed, very keyed but very effective), it would load it, The class information in the. class file is then generated to produce a unique class object that is associated with the class. The Class object records the fields, methods, and so on for this kind of information. Later, the JVM will generate an instance of the class, based on the information that exists in memory for that class (the class object should be generated and extinct in heap memory just like any other Class I know).

The class object in Java can be artificially natural (that is, open) (though you can't use a constructor like any other class to get an instance of it, because

Class objects are generated by the JVM. But then again, the customer's words are meaningless, and, even greater, based on this foundation, Java implements the reflection mechanism.

There are three ways to get a class object:

1. Pass the GetClass () method of the object class. For example:

Class C1 = new String (""). GetClass ();

2. Using the class class static method--forname () to achieve:

Class C2 = class.forname ("MyObject");

3. If T is a defined type, in Java, its. class file name: T.class represents the class object that matches it, for example:

Class C3 = Manager.class;

Class C4 = int.class;

Class c5 = double[].class;

Here's what you need to explain 3: Remember, in Java, everything is object. That is, the base type int float is also generated in the JVM's memory pool like other types

A Class object . Combined data types, such as arrays, generate a class object, and more surprisingly, the true nature of an array in Java is a class, which is surprisingly

The surprise is that an array of the same number of dimensions with the same elements will also share the same class object! In fact, according to my assumptions, the length property of the array should be stored in this class

Object inside.

There are several important ways to do this in class:

1.getName ()

A class object describes a particular property of a particular class, and this method returns a brief description of the class in string form. For historical reasons, the class object of the array

Calling this method can produce strange results.

2.newInstance ()

The method can produce an instance of its corresponding class based on a class object. It is to be emphasized that it calls the default constructor method for this class. For example:

MyObject x = new MyObject ();

MyObject y = X.getclass (). newinstance ();

3.getClassLoader ()

Returns the class loader for the class corresponding to this class object.

4.getComponentType ()

This method, for the class object of the array object, can get the class object of the corresponding object of the array's constituent elements. For example:

int[] ints = new int[]{1,2,3};

Class Class1 = Ints.getclass ();

Class Class2 = Class1.getcomponenttype ();

The Class2 object you get here should be the class object of the primitive type int.

5.getSuperClass ()

Returns the class object corresponding to the immediate parent class for a subclass.

6.isArray ()

Determines whether this class object corresponds to an array object.

Well, now we have a general idea of class, and here's a typical example of a reflection mechanism for you to analyze:

ImportJava.lang.reflect.Array; ImportJava.lang.reflect.Constructor; ImportJava.lang.reflect.Field; ImportJava.lang.reflect.Method; /*** Java Reflection Cookbook * *@authorMichael Lee *@since2006-8-23 *@version0.1a*/         Public classReflection {/*** Get the public properties of an object * *@paramowner, FieldName *@returnthe Property Object *@throwsException **/         PublicObject GetProperty (object owner, String fieldName)throwsException {Class Ownerclass=Owner.getclass (); Field field=Ownerclass.getfield (fieldName); Object Property=Field.get (owner); returnProperty ; }             /*** Get static public properties of a class * *@paramClassName class name *@paramFieldName Property name *@returnthe Property Object *@throwsException*/         PublicObject Getstaticproperty (String className, string fieldName)throwsException {Class Ownerclass=Class.forName (className); Field field=Ownerclass.getfield (fieldName); Object Property=Field.get (Ownerclass); returnProperty ; }                 /*** Execute an object method * *@paramOwner * Object *@paramMethodName * Method Name *@paramargs * Parameters *@returnmethod return value *@throwsException*/         PublicObject InvokeMethod (object owner, String methodName, object[] args)throwsException {Class Ownerclass=Owner.getclass (); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Method=Ownerclass.getmethod (MethodName, Argsclass); returnMethod.invoke (owner, args); }                   /*** Perform a static method of a class * *@paramClassName * Class name *@paramMethodName * Method Name *@paramargs * parameter array *@returnresults returned by the execution method *@throwsException*/         PublicObject Invokestaticmethod (String className, String methodName, object[] args)throwsException {Class Ownerclass=Class.forName (className); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Method=Ownerclass.getmethod (MethodName, Argsclass); returnMethod.invoke (NULL, args); }                     /*** NEW instance * *@paramClassName * Class name *@paramargs * Parameters of the constructor *@returnnew instance *@throwsException*/         PublicObject newinstance (String className, object[] args)throwsException {Class Newoneclass=Class.forName (className); Class[] Argsclass=NewClass[args.length];  for(inti = 0, j = args.length; I < J; i++) {Argsclass[i]=Args[i].getclass (); } Constructor Cons=Newoneclass.getconstructor (Argsclass); returncons.newinstance (args); }                          /*** is not an instance of a class *@paramobj Instance *@paramCLS class *@returnreturns True if obj is an instance of this class*/         Public Booleanisinstance (Object obj, Class cls) {returncls.isinstance (obj); }                  /*** Get an element in the array *@paramArray Arrays *@paramIndex Indices *@returnreturns the value of the index component in the specified array object*/         PublicObject Getbyarray (Object array,intindex) {             returnArray.get (Array,index); }     }

On the reflection mechanism of Java

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.