Fun java (2)-generic type system and reflection

Source: Internet
Author: User

I. Type

Type is a common parent interface of all types in Java programming language. These types include raw types, parameterized types, array types, type variables, and primitive types ). We generally do not directly operate the Type, but it is necessary to understand the hierarchy of the Type.

1. Type hierarchy


2. Inheritance System of Class, Method, and Field


Ii. Type and reflection

The reflection mechanism allows the program to obtain the internal information of any class with a known name at runtime, allowing the program to load, explore, and use classes unknown during compilation. That is, the reflection mechanism of Java can load a class that is known only during runtime to obtain its complete structure.

1. Foundation of reflection: Class

During the running of the program, the Java runtime system always maintains a type identifier called runtime for all objects. This information stores the class footprint of each object. The virtual machine uses the running information to select the corresponding method for execution. However, you can access this information through a dedicated Java class. The Class that stores the information is called Class, and the generic form is Class. . Class is the basis of the reflection mechanism. The reflection API obtains its complete structure by operating on the Class.

Common Methods for getting a Class:

Call getClass () (The getClass () method in the Object Class returns an instance of the Class type)

Boolean var1 = true; Class ClassType2 = var1.getClass (); System. out. println (classType2); output: class java. lang. Boolean

Use the T. class syntax (T is any Java type)

Class ClassType4 = Boolean. class; System. out. println (classType4); output: class java. lang. Boolean

Use static method Class. forName () (exception processor should be provided in use)

Class ClassType5 = Class. forName ("java. lang. Boolean"); System. out. println (classType5); output: class java. lang. Boolean

Use the TYPE Syntax of primitive wrapper classes (the native TYPE is returned here, which is different from the TYPE returned by Boolean. class)

Class ClassType3 = Boolean. TYPE; System. out. println (classType3); output: boolean


Note: A Class Object actually represents a type, which is not necessarily a type. For example, int Is not a class, but int. Class is a class object. A Virtual Machine manages a Class Object for each type. Therefore, you can use the = Operator to compare two class objects.

Common Methods of Class:

Method

Description

Example

GetName ()

Return Class Name

String. class. getName ();

Return Value: "java. lang. String"

NewInstance ()

Quickly create an instance of a class (call the default constructor, if the class does not have the default constructor, an exception is thrown) (if you want to provide parameters for the constructor, make java. lang. reflect. the newInstance method in Constructor)

String s = "java. util. Date ";

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

GetSuperclass ()

Returns a superclass.

GetFields () getMethods () getConstructors () (also contains string parameters, given names)

Return the supportedPublicFields, methods, and constructor arrays, including the public members of superclasses

GetDeclaredFields ()

GetDeclaredMethods ()

GetDeclaredConstructors () (also in the form of a given name)

Return the declaredAllArray of fields, methods, and constructors. This includes private and protected members, but does not include super-class members.


2. Use the Reflection Analysis class

A class consists of modifiers, fields, constructors, and methods. The Field, Method, and Constructor classes are used to describe the domain, Method, and Constructor of the class respectively. In addition, the Modifier class in the java. lang. reflect package can analyze access modifiers. You can use them to analyze classes.

Common analysis methods:

Class Method Function
Field
Method
Constructor
Class getDeclaringClass () Returns a Class object that describes the constructors, methods, or fields 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 different bits.

Method

Constructor

Class [] getExceptionTypes ()

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

Class [] getParameterTypes ()

Returns an array of Class objects used to describe the parameter type.

Field

Class getType ()

Returns the Class object that describes the type of the domain.

Modifier

Static String toString (int modifiers)

Returns the string representation of the modifier corresponding to the modifiers bit.

Static boolean isXXX (int modifiers)

Check the modifiers value of the modifier corresponding to the method name.

Access permission issues:

Because the default behavior of the reflection mechanism is restricted by Java access control, for example, access to private methods and fields, unless you have access permissions, the Java security mechanism allows you to view the domains of any objects, they are not allowed to read their values (an exception is thrown during reading ). However, if a Java program is not controlled by the security manager, it can overwrite access control. To achieve this goal, you need to call the setAccessible () Method of the Field, Method, and Constructor object.

Function

Function

Void setAccessible (boolean flag)

Set the accessible flag for the reflected object. If the flag is true, the Java language access check is blocked, so that the private attributes of the object can be queried and set.

Boolean isAccessible ()

Returns the accessible flag value of the reflected object.

Static void setAccessible (AccessibleObject [] array, boolean flag)

A shortcut for setting the accessible flag of an object Array

3. A classic reflection tool class

Package study. java. core. util; import java. lang. reflect. array; import java. lang. reflect. constructor; import java. lang. reflect. field; import java. lang. reflect. method;/*** reflection tool class * @ author qbg **/public abstract class ReflectUtil {/*** get the attributes of an Object */public Object getProperty (Object owner, string fieldName) throws Exception {// 1. The Class of the object is obtained. Class
 OwnerClass = owner. getClass (); // 2. Get the attributes declared by Class through Class. Field field = ownerClass. getField (fieldName); // 3. The instance that obtains this attribute through the object. If this attribute is private, IllegalAccessException will be thrown here. Object property = field. get (owner); // The Object property is obtained here, so the owner is passed. Return property;}/*** get the static attribute of a Class */public Object getStaticProperty (String className, String fieldName) throws Exception {// 1. Get the Class of this Class. Class
 OwnerClass = Class. forName (className); // 2. Get the attributes declared by Class. Field field = ownerClass. getField (fieldName); // 3. Because the obtained static attribute is passed as a Class, the static attribute is obtained directly from the Class. Object property = field. get (ownerClass); return property;}/*** Method for executing an Object */public Object invokeMethod (Object owner, String methodName, Object [] args) throws Exception {// 1. Get the Class of the object. Class
 OwnerClass = owner. getClass (); // 2. Assemble the Class array of the parameter to match the condition Class of Method.
 [] ArgsClass = new Class
 [Args. length]; for (int I = 0; I ownerClass = Class. forName (className); // 2. Assemble the Class array of the parameter to match the condition Class OF THE Method
 [] ArgsClass = new Class
 [Args. length]; for (int I = 0; I newOneClass = Class. forName (className); // 2. Obtain the Class array Class of the parameter.
 [] ArgsClass = new Class
 [Args. length]; for (int I = 0; I ctor = newOneClass. getConstructor (argsClass); // 4. Create an instance return ctor. newInstance (args);}/*** determine whether it is an instance of a Class */public boolean isInstance (Object obj, Class
 Clazz) {return clazz. isInstance (obj);}/*** get an element in the array */public Object getByArray (Object Array, int index) {return array. get (array, index );}}

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.