Re-describing Java reflection

Source: Internet
Author: User
Tags modifiers

Reflection in Java

This document is the basic knowledge part of reflection.

A program capable of analyzing classes is called reflection (reflective).

  The reflection mechanism allows the program to obtain the internal information of any known-named class at run time, allowing the program to load, detect, and use classes unknown during compilation at run time. That is, the reflection mechanism of Java can load a runtime to know the name of the class, get its full structure.

A Class

During a program run, the Java Runtime system always maintains a type identity known as the runtime for all objects.

This information holds the class footprints that each object belongs to. The virtual machine uses the run-time information to select the appropriate method to execute.

However, this information can be accessed through a specialized Java class. The classes that hold this information are called class.

(Note: The new version is class<t> This article is often used to write class only)

API:java.lang.Class

(1.7) http://docs.oracle.com/javase/7/docs/api/index.html

To obtain the class object of the method:

Call GetClass ()

(The GetClass () method in the object class returns an instance of class type)

Boolean var1 = true; class<?> classType2 = Var1.getclass (); System.out.println (classType2); Output: Class Java.lang.Boolean

Using T.class syntax

(T is any Java type)

class<?> classType4 = Boolean.class; System.out.println (CLASSTYPE4); Output: Class Java.lang.Boolean

Using the static method Class.forName ()

(Exception handler should be provided when used)

class<?> ClassType5 = Class.forName ("Java.lang.Boolean"); System.out.println (CLASSTYPE5); Output: Class Java.lang.Boolean

Using the type syntax of primitive wrapper classes

(The native type is returned here, and the Boolean.class return is different)

class<?> classType3 = boolean.type; System.out.println (CLASSTYPE3); output: Boolean

A class object actually represents a type, and this type may not necessarily be a class.

For example, int is not a class, but Int.class is an object of type class.

  a virtual machine manages a class object for each type . Therefore, you can use the = = operator to achieve the operation of two class object comparisons (different class loaders load the same class file to get different classes).

The most common class Method:

Method

Description

Example

GetName ()

Returns the name of the class

String.class.getName ();

return: "Java.lang.String"

Newinstance ()

To quickly create an instance of a class

(Call the default constructor, throw an exception if the class does not have a default constructor)

(If you want to supply parameters for the constructor, use the Newinstance method in Java.lang.reflect.Constructor)

String s = "java.util.Date";

Object m = Class.forName (s). newinstance ();

Getsuperclass ()

Back to Super class

GetFields () GetMethods () GetConstructors () (also with a string argument, given the form of a name)

Returns the public domain, method, and constructor arrays supported by the class, including the members of the superclass

Getdeclaredfields ()

Getdeclaredmethods ()

Getdeclaredconstructors ()

(also in the form of a given name)

Returns the entire array of fields, methods, and constructors declared in the class, respectively. This includes private and protected members, but does not include members of the superclass

Two Java.lang.reflect Bag

The return values of the GetFields (), GetMethods (), GetConstructors () methods in the class mentioned above are specific types (Field, Method, constructor class ) the array type.

The field, method, constructor class, respectively, are used to describe the class's fields, methods, and constructors, both in the Java.lang.reflect package.

The Java.lang.reflect package provides reflection-related api,1.7.0 reflect packages such as:

(http://docs.oracle.com/javase/7/docs/api/java/lang/reflect/package-frame.html)

2.1 Using the Reflection Analysis class

As mentioned earlier, the field, method, and constructor classes are used to describe the class's fields, methods, and constructors, respectively. In addition, the modifier class in the Java.lang.reflect package can parse the access modifier. Then use them to analyze the class.

Common methods for analyzing classes:

Class Method Role
Fieldmethodconstructor Class Getdeclaringclass () Returns a class object that describes the constructor, method, or field defined in the class
String GetName () Returns the name of the corresponding entry
int getmodifiers () Returns an integer value that describes the usage of the access modifier with a different bit switch

Method

Constructor

Class[] Getexceptiontypes ()

Returns an array of class objects that describe the type of exception thrown by the method

Class[] Getparametertypes ()

Returns an array of class objects that describe the type of the parameter

Field

Class GetType ()

Used to return a class type object that describes the type of the domain

Modifier

static String toString (int modifiers)

Returns the string representation of the modifier for the corresponding modifiers bit setting

Static boolean isxxx (int modifiers)

Detecting the value of the corresponding modifier in the method name in the modifiers

2.2 Analyzing objects with reflection

Section 2.1 already knows how to view the data field name and type of any object, in this section, you will see the actual contents of the data field . The reflection mechanism allows you to view object fields that are not yet clear at compile time.

The key method for viewing object fields is the Get method in the field class.

If f is an object of type field (for example, an object obtained through GetField (String name), and obj is an object of a class that contains an F field, then f.get (obj) returns an object whose value is the current value of the F field of obj.

Can be set by the fetch, call F.set (obj,value) to set the F field of the Obj object to the new value.

Access rights issues

In the example above, if the field is a private domain, the Get method throws an exception.

This is because the default behavior of the reflection mechanism is limited to Java access control, for example, unless you have access, Java security allows you to see which fields are available for any object and not to read their values.

However, if a Java program is not under the control of the security manager, access control can be overridden. To achieve this, you need to invoke the setaccessible method of the field, method, constructor object.

Field, Method, constructor class are derived from accessibleobject.

AccessibleObject Common methods:

Function

Role

void Setaccessible (Boolean flag)

Setting an accessible flag for the reflected object, flag True indicates that the access check is masked by the Java language, so that the object's private properties can also be queried and set

Boolean isaccessible ()

Returns the value of an accessible flag for a reflected object

static void Setaccessible (Accessibleobject[] Array, Boolean flag)

A quick way to set accessible flags for an array of objects

Please see the original http://www.cnblogs.com/mengdd/archive/2012/08/18/2645553.html

Re-describing Java reflection

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.