Play Java (2)-generic type System and reflection

Source: Internet
Author: User
Tags modifier modifiers reflection

Types of type

Type is the normal parent interface for all types in the Java programming language. These types include the native type (raw types), the parameterized type (parameterized types), the array type (array types), the type argument (type variables), and the original type (primitive types). We generally do not manipulate type types directly, but it is necessary to understand the hierarchy of type types.

1, type hierarchy


2, the inheritance system of class,method and field


Two, type and reflection

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

1, the basis of reflection: Class

During a program run, the Java Runtime system always maintains a type identity known as the runtime for all objects. This information preserves the class footprint of each object. The virtual machine uses run-time information to select the appropriate method to execute. However, this information can be accessed through specialized Java classes. The class that holds the information is called class, and the generic form is class<t>. Class is the basis of the reflection mechanism, and the reflection API obtains its complete structure by manipulating class.

Common ways to get 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

Using 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 handler should be provided when used)

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

Use the type syntax of the 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


Note: 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 class type. Virtual machines manage a class object for each type. Therefore, you can use the = = operator to implement the operations of two class object comparisons. Class Common methods:

Method

Description

Example

GetName ()

Returns the name of the class

String.class.getName ();

Back: "Java.lang.String"

Newinstance ()

Quickly create an instance of a class (calling the default constructor, throwing an exception if the class does not have a default constructor) (if you want to supply arguments to the constructor, make 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 string arguments, 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 all the fields, methods, and constructor arrays declared in the class, respectively. These include private and protected members, but not members of the superclass


2, the use of reflection analysis class

A class is composed primarily of modifiers, fields, constructors, and methods, while field, method, and constructor classes are used to describe the domain, methods, and constructors of the class, 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
Field
Method
Constructor
Class Getdeclaringclass () Returns a class object that describes the constructor, method, or field defined in a 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 a method

Class[] Getparametertypes ()

Returns an array of class objects used to describe parameter types

Field

Class GetType ()

Class type Object to return the type of the description domain belongs to

Modifier

static String toString (int modifiers)

Returns a string representation of the modifier corresponding to the modifiers bit setting

Static boolean isxxx (int modifiers)

The value of the corresponding modifier in the modifiers in the detection method name

Access Permissions Issue:

Because the default behavior of reflection mechanisms is restricted to Java access control, for example, access to private methods, fields, unless you have access rights, the Java security mechanism allows you to see which fields are in any of the objects and not to read their values (reads will throw exceptions). 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 call the Setaccessible () method of the field, methods, and constructor objects.

Function

Role

void Setaccessible (Boolean flag)

Setting an accessible flag for the reflection object, flag to TRUE indicates that the access checks for the Java language are masked so that the private properties of the object 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 an accessible flag for an object array

3, a classic reflective 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 properties of an object/public object Getpropert
		Y (object owner, String fieldName) throws Exception {//1, gets the class of the object.
		class<?> Ownerclass = Owner.getclass ();
		2. The attribute of class declaration is obtained by class.
		Field field = Ownerclass.getfield (FieldName);
		3, through the object to get this attribute instance, if this property is private, here will throw illegalaccessexception. Object property = Field.get (owner);
		The property of the object is obtained here, so the owner is passed.
	return property; /** * Gets the static properties of a class/public Object Getstaticproperty (String classname,string fieldName) throws exception{//1,
		To class.
		class<?> Ownerclass = Class.forName (className);
		2. The attribute of class declaration is obtained by class.
		Field field = Ownerclass.getfield (FieldName);
		3, as the acquisition of static properties, here passed as class, directly from the class to get static properties. 
		Object property = Field.get (Ownerclass);
	return property;
	
	}/** * method to execute 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, the Class array of assembly parameters, used to match the conditions of method class<?>[] Argsclass = new class<?>[args.length];
		for (int i=0; i<args.length; i++) {Argsclass[i] = Args[i].getclass ();
		//3, by using the method name and the class array of the parameters to get the method method to be executed = Ownerclass.getmethod (methodname, Argsclass);
		4. Invoke invoke execution method. This is the owner that is passed here because of the way the object is executed.
	Return Method.invoke (owner, args); /** * static method of executing class */public Object Invokestaticmethod (String classname,string methodname,object[] args) throws Exce
		ption{//1, get class.
		class<?> Ownerclass = Class.forName (className);
		2, the Class array of assembly parameters, used to match the conditions of method class<?>[] Argsclass = new class<?>[args.length];
		for (int i=0; i<args.length; i++) {Argsclass[i] = Args[i].getclass (); //3, using the class array of the method name and parameter to get the method method to execute = Ownerclass.getmetHod (methodname, Argsclass);
		4. Invoke invoke execution method. Because the static methods of the class are executing, there is no need to use the object instance, which is passed null.
	return Method.invoke (null, args); /** * Creates a new instance.
	 invokes the parameter constructor. */Public Object newinstance (String classname,object[] args) throws exception{//1, get the Class class<?> to construct the instance
		Eclass = Class.forName (className);
		2, get the parameter Class array class<?>[] Argsclass = new class<?>[args.length]; 
		for (int i=0; i<args.length; i++) {Argsclass[i] = Args[i].getclass ();
		}//3, get the constructor constructor<?> ctor = Newoneclass.getconstructor (Argsclass);
	4, new instance return ctor.newinstance (args); 
	/** * To determine if it is an instance of a class/public boolean isinstance (Object obj,class<?> clazz) {return clazz.isinstance (obj);
	/** * Gets 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.