Java Advanced Reflection __java

Source: Internet
Author: User
Tags date1 documentation modifier reflection static class stringbuffer
1 The cornerstone of reflection classes class 1.Java class is used to describe the generality of a class of things, what attributes, what attributes, and what the value of this property is, is determined by the instance object of the class, and different instance objects have different attribute values. Java programs in Java classes, whether they belong to the same kind of things, it is possible to use a class to describe such things. The name of this class is class, pay attention to the difference with the lowercase class keyword OH. What kinds of information are described in class classes? The name of the class, the Access property of the class, the package name that the class belongs to, the list of field names, the list of method names, and so on. To learn reflection, one must first understand class. Write the following code to compare and understand:
/*person P1 = new Person ("Zhangsan");
person P2 = new Person ("Lisi");
*/
/*class x1 = byte code of vector class in memory
Class x2 = The byte code in memory of the date class * *
Class x1 = vector.class;
Class x2 = date.class;

Each Java class is an instance object of class, and their contents are different, but they have the same characteristics, for example, there are methods, fields, parent classes, and packages.
2. When the lecture must draw a picture: Multiple classes of bytecode loaded into memory, in memory to add a block space to represent the bytecode, and then use an ellipse to represent the creation of the byte code of the instance object, and monitoring code to illustrate that the bytecode is only loaded once, The construction method of the instance object it constructs is called several times. Use the following code to further explain what an instance of class is. is a byte code, a class usually has only one byte code in the virtual machine:
Date D1 = new Date ();
Class clazz1 = D1.getclass ();
Class clazz2 = Date.class;
Class clazz3 = null;
Clazz3 = Class.forName ("Java.util.Date");

if (CLAZZ1==CLAZZ2)
{
System.out.println (Clazz1.getname ());
}
if (CLAZZ1==CLAZZ3)
{
System.out.println (Clazz1.getname ());
}
3. A strange question: The byte code is loaded and the method of its getmethods is invoked, but the static code block of the class is not seen to be executed, and the static code is executed only when the first instance object is created. To be exact, a static code block is not invoked when the class is loaded, but is executed when the first instance object is created.




Reflection of the Cornerstone--class class

Contrast questions: Person class representative, it's instance object is John, dick such a specific person, Java program Java class belongs to the same kind of things, describe this kind of things Java class name is class. Compare questions: A large number of people are represented by what class. Many Java classes are represented in one of the classes.
People--person
Java class--class

Class classes represent Java classes, and what each instance object corresponds to.
Corresponds to the byte code of each class in memory, for example, the byte code of the Person class, the byte code of the ArrayList class, and so on.
A class is loaded into memory by the class loader, occupy a storage space, the contents of this space is the byte code of the class, different classes of the byte code is different, so they in the contents of memory is different, this space can be used to each individual object to represent, these objects obviously have the same type, What is this type of thing?

How to get the instance object (class type) corresponding to each byte code
Class name. Class, for example, System.class
Object. GetClass (), for example, New Date (). GetClass ()
Class.forName ("Class name"), for example, Class.forName ("java.util.Date");

Nine predefined class instance objects:
See Help with the Class.isprimitive method
Int.class = = Integer.type

Class instance object of array type
Class.isarray ()
In short, as long as the type that appears in the source program, has its own class instance object, for example, int[],void ...

Demo:view Plain Copy to clipboard print? package cn.itcast;      import java.util.date;     /**  * Test whether three bytecode is the same byte code   * @author partner4java  *  */   public class reflecttest1 {        public static void main (string[] args)  throws  ClassNotFoundException {           date Date = new  Date ();           class date1 = Date.getclass ();           class date2 = Class.forName ("java.util.Date");            system.out.println ("date1 = = date2?")  + (date1 = = date2));                       class date3 = date.class;      &nbsP;    system.out.println ("date1 = = date3?")  + (date1 = = date3));             //        background print:  //      date1 = = Date2?true  //       date1 = = Date3?true          }      }  




Class JDK Documentation:

Public final class Class<t>extends objectimplements Serializable, genericdeclaration, Type, An instance of the Annotatedelementclass class represents a class and interface in a running Java application. An enumeration is a class, and a comment is an interface. Each array belongs to a class that is mapped to the class object, and all arrays that have the same element type and number of dimensions share the class object. Basic Java Types (Boolean, Byte, char, short, int, long, float, and double) and keyword Void are also represented as Class objects.

Class does not have a public constructor method. Class objects are automatically constructed by the Java virtual machine and by invoking the DefineClass method in the ClassLoader when loading the class.

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


void Printclassname (Object obj) {
System.out.println ("The Class of" + obj +
"Is" + obj.getclass (). GetName ());
}
You can also use a class literal (JLS section 15.8.2) to get a class object of a named type (or void). For example:


System.out.println ("The name of Class Foo is:" +foo.class.getname ());



Method Summary
<U> class<? Extends u>
Assubclass (class<u> clazz)
Casts the class object to represent a subclass of the class represented by the specified class object.
T cast (Object obj)
Casts an object to the class or interface represented by this class object.
Boolean desiredassertionstatus ()
If you want to initialize the class when this method is called, the assertion state that will be assigned to the class is returned.
Static class<?> forname (String className)
Returns the class object associated with the class or interface with the given string name.
Static class<?> forname (String name, Boolean initialize, ClassLoader loader)
Returns the class object associated with the class or interface with the given string name, using the given class loader.
<a extends Annotation>
A
Getannotation (class<a> annotationclass)
If a comment of the specified type of the element exists, the comments are returned, or null is returned.
Annotation[] Getannotations ()
Returns all annotations that exist on this element.
String Getcanonicalname ()
Returns the canonical name of the underlying class as defined in the Java Language specification.
Class[] Getclasses ()
Returns an array of some class objects representing all the public classes and interfaces that belong to the members of the class represented by this class object, including the public class and interface members that are inherited from superclass and public classes and declared through the class.
ClassLoader getClassLoader ()
Returns the class loader for the class.
Class<?> Getcomponenttype ()
Returns the Class that represents the type of the array component.
Constructor<t> getconstructor (Class ... parametertypes)
Returns a constructor object that reflects the specified public constructor method for the class represented by this class object.
Constructor[] GetConstructors ()
Returns an array of some constructor objects that reflect all the public constructor methods of the class represented by this class object.
Annotation[] Getdeclaredannotations ()
Returns all comments that exist directly on this element.
Class[] Getdeclaredclasses ()
Returns an array of class objects that reflect all the classes and interfaces that declare the members of the class represented by this class object, including the public, protection, default (package) access and private classes and interfaces declared by the classes, but excluding inherited classes and interfaces.
Constructor<t> getdeclaredconstructor (Class ... parametertypes)
Returns an constructor object that reflects the specified construction method of the class or interface represented by this class object.
Constructor[] Getdeclaredconstructors ()
Returns an array of constructor objects that reflect all the constructed methods of the class declaration represented by this class object.
Field Getdeclaredfield (String name)
Returns a Field object that reflects the specified declared field of the class or interface represented by this class object.
Field[] Getdeclaredfields ()
Returns an array of field objects that reflect all the fields declared by the class or interface represented by this class object, including public, protected, default (package) access, and private fields, but excluding inherited fields.
Method Getdeclaredmethod (String name, Class ... parametertypes)
Returns a method object that reflects the specified declared methods of the class or interface represented by this class object.
Method[] Getdeclaredmethods ()
Returns an array of method objects that reflect all the methods declared by the class or interface represented by this class object, including public, protection, default (package) access, and private methods, but excluding inherited methods.
Class<?> Getdeclaringclass ()
If the class or interface represented by this class object is a member of another class, the returned class object represents the declared class of the object.
Class<?> Getenclosingclass ()
Returns the immediate enclosing class of the underlying class.
Constructor<?> Getenclosingconstructor ()
If the class object represents a local or anonymous class in a constructor, it returns a constructor object that represents the immediate enclosing construction method of the underlying class.
Method Getenclosingmethod ()
If this class object represents a local or anonymous class in a method, it returns the method object, which represents an immediate enclosing of the underlying class.
T[] Getenumconstants ()
If this class object does not represent an enumeration type, the element or null of the enumeration class is returned.
Field GetField (String name)
Returns a Field object that reflects the specified public member field of the class or interface represented by this class object.
Field[] GetFields ()
Returns an array containing some field objects that reflect all accessible public fields of the class or interface represented by this class object.
Type[] Getgenericinterfaces ()
Returns the type representing some interfaces that are implemented directly by the class or interface represented by this object.
Type Getgenericsuperclass ()
Returns the type of the direct superclass that represents the entity (class, interface, base type, or void) represented by this class.
Class[] Getinterfaces ()
Determines the interface implemented by the class or interface represented by this object.
Method GetMethod (String name, Class ... parametertypes)
Returns a method object that reflects the specified public member methods of the class or interface represented by this class object.
Method[] GetMethods ()
Returns an array of some method objects that reflect the public member methods of the class or interface represented by this class object, including those declared by that class or interface, and those inherited from superclass and hyper interfaces.
int getmodifiers ()
Returns the Java language modifier for this class or interface encoded in integers.
String GetName ()
Returns the name of the entity (class, interface, array class, base type, or void) represented by this class object as a String.
Package Getpackage ()
Gets the package for this class.
Protectiondomain Getprotectiondomain ()
Returns the Protectiondomain of the class.
URL getresource (String name)
Finds a resource with the given name.
InputStream getResourceAsStream (String name)
Finds a resource with the given name.
Object[] Getsigners ()
Gets the token for this class.
String Getsimplename ()
Returns the abbreviation for the underlying class given in the source code.
class<? Super T> Getsuperclass ()
Returns the class of the superclass that represents the entity (class, interface, base type, or void) represented by this class.
Typevariable<class<t>>[] Gettypeparameters ()
Returns an array of Typevariable objects in the declared order that represent the type variables declared with the general declaration represented by this Genericdeclaration object.
Boolean isannotation ()
Returns true if this Class object represents an annotation type.
Boolean isannotationpresent (class<? extends annotation> Annotationclass)
Returns true if a comment of the specified type exists on this element, or false.
Boolean Isanonymousclass ()
Returns true if and only if the underlying class is an anonymous class.
Boolean IsArray ()
Determines whether this class object represents an array class.
Boolean IsAssignableFrom (class<?> CLS)
Determines whether the class or interface represented by this class object is the same as the class or interface represented by the specified class parameter, or whether it is a superclass or a super interface.
Boolean isenum ()
Returns true if and only if the class is declared as an enumeration in source code.
Boolean isinstance (Object obj)
Determines whether the specified object is assignment-compatible with the object represented by this Class.
Boolean isinterface ()
Determines whether the specified Class object represents an interface.
Boolean Islocalclass ()
Returns true if and only if the underlying class is a local class.
Boolean Ismemberclass ()
Returns true if and only if the underlying class is a member class.
Boolean isprimitive ()
Determines whether the specified Class object represents a basic type.
Boolean issynthetic ()
Returns true if this class is a composite class, or false.
T newinstance ()
Creates a new instance of the class represented by this class object.
String toString ()
Converts an object to a string.



2 Reflection

Reflection is the mapping of various components in a Java class to the corresponding Java class. For example, a Java class is represented by an object of a class class, and the components of a category: member variables, methods, constructs, packages, and so on, are also represented by a Java class, like a car is a class, an engine in a car, a gearbox, and so on. Class classes that represent Java classes clearly provide a series of methods for obtaining variables, methods, constructs, modifiers, packages, and so on, which are represented by instance objects of the corresponding class, which are field, method, Contructor, package, and so on.
Each member of a class can be represented by an instance object of the corresponding reflection API class, and what is the use of these instance objects after they are obtained by invoking the method of the class class? How to use it. This is the main point of learning and applying reflection.



3Constructor class
The constructor class represents a constructor method in a class

Get all the construction methods for a class:
Example: constructor [] constructors= class.forname ("java.lang.String"). GetConstructors ();

To get a construction method:
Example: constructor constructor = Class.forName ("java.lang.String"). GetConstructor (Stringbuffer.class);
Type used when getting methods

To create an instance object:
Usual way: String str = new string (New StringBuffer ("abc"));
Reflection mode: String str = (string) constructor.newinstance (new StringBuffer ("abc"));
When you call the obtained method, you use an instance object of the same type above

Class.newinstance () Method:
Example: String obj = (string) class.forname ("java.lang.String"). newinstance ();
The method internally gets the default construction method, and then creates the instance object with the constructor method.
What is the specific code inside the method written? The caching mechanism is used to hold the instance object of the default constructor method.





constructor<t> JDK Documentation:
Public final class Constructor<t>extends accessibleobjectimplements genericdeclaration, Memberconstructor Provides information about a single construction method of a class and its access rights.

constructor allows extended conversions when a newinstance () that is actually participating in a formal parameter with the underlying construction method is matched, but throws a illegalargumentexception if a narrowing conversion occurs.

Method Summary
Boolean equals (Object obj)
Compares this constructor object with the specified object.
<t extends Annotation>
T
Getannotation (class<t> annotationclass)
If a comment of the specified type of the element exists, the comments are returned, or null is returned.
Annotation[] Getdeclaredannotations ()
Returns all comments that exist directly on this element.
Class<t> Getdeclaringclass ()
Returns a Class object that represents the classes that declare the construction method represented by this constructor object.
Class<?>[] Getexceptiontypes ()
Returns a set of Class objects that represent the type of exception declared to be thrown, which are thrown by the underlying construction method represented by this constructor object.
Type[] Getgenericexceptiontypes ()
Returns a set of Type objects that represent the exceptions that are declared to be thrown by this constructor object.
Type[] Getgenericparametertypes ()
Returns a set of type objects that represent the formal parameter type of the method represented by this constructor object, in the declared order.
int getmodifiers ()
Returns the Java language modifier for the constructed method represented by this constructor object as an integer.
String GetName ()
Returns the name of this constructed method as a string.
Annotation[][] Getparameterannotations ()
Returns a set of arrays in the declared order that represent comments on the parameters of the method represented by this methods object.
Class<?>[] Getparametertypes ()
Returns a set of Class objects in the declared order that represent the formal parameter types of the constructed method that this constructor object represents.
Typevariable<constructor<t>>[] Gettypeparameters ()
Returns a set of Typevariable objects in the declared order that represent the type variables declared through the general declaration represented by this Genericdeclaration object.
int Hashcode ()
Returns the hash code for this constructor.
Boolean issynthetic ()
Returns true if this constructor is a composite construction method, otherwise false.
Boolean Isvarargs ()
Returns true if the constructor can be declared with a variable number of arguments, otherwise it returns false.
T newinstance (Object ... initargs)
Creates a new instance of the Declaration class for the constructor by using the constructor represented by this constructor object, and initializes the instance with the specified initialization parameter.
String togenericstring ()
Returns a string that describes this constructor, including the type parameter.
String toString ()
Returns a string that describes this constructor.





4Field class
View plain Copy to clipboard print? The field class represents a member variable in a class       reflectpoint point = new reflectpoint (1,7);   Field y = class.forname ("Cn.itcast.corejava.ReflectPoint"). GetField ("y");   System.out.println (Y.get ( Point));  //field x = Class.forName ("Cn.itcast.corejava.ReflectPoint"). GetField ("x");   Field X = Class.forName ("Cn.itcast.corejava.ReflectPoint"). Getdeclaredfield ("x");   x.setaccessible (true);   
Related Article

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.