Java notes (5) -- Reflection

Source: Internet
Author: User

1. Why reflection:
If an external Object is received when the program runs, the compilation type of the Object is Object, but the program needs to call the method of the Object running type:
(1). If the compilation and running types are all known, use instanceof to determine and convert the statements.
(2) during compilation, the class of the object cannot be predicted at all. The program can only rely on runtime information to discover the real information of the object, and reflection must be used.
(3) If you want to get the real object type, you must use reflection.
2. The most important role of reflection is in the Framework. The powerful functions are at the cost of performance!
3. Instances of the class and class:
Each Java Class in a Java program belongs to the same Class of things. The Java Class that describes such things is the Class.
Comparison question: what kind of representation does most people use? What classes are used to represent many Java classes?
Persons? Person
Java class? Class
Comparison question: the Person Class representative, its instance object is Zhang San, Li Si, such a specific Person, Class represents Java Class, what corresponding to its various instance objects?
Corresponding to the bytecode of each class in the memory, such as the Person class, the ArrayList class, and so on;
A class is loaded into the memory by the class loader and occupies a storage space. The content in this space is the class bytecode. the bytecode of different classes is different, therefore, their content in the memory is different;
A class has only one bytecode in a virtual machine;
4. Three Methods of getting the Class object are as follows:
(1). Pass the class attribute of the class;
Class. class;
(2). Use Class. forName (String className); className to indicate the full qualified name of a Class.
Class clz = Class. forName ("java. util. Date ");
In this case, clz describes the java. util. Date class.
(3). It can be done through a getClass () method of the object.
Class GetClass () returns the runtime class of this Object.


5. Nine predefined objects:
Basic Java types (boolean, byte, char, short, int, long, float, and double)
And the keyword void are also represented as Class objects.
They all correspond to this class attribute;
(1). Their conversion classes all have TYPE constants. What they get is the bytecode of their basic types;
Data Types (references and basics) all have class attributes;
(2). Arrays with the same element type and dimension share the same Class object.
It is independent of the number of elements in the array, the value of the element, and the sequence of the element.
6. Use reflection to create objects
(1 ).
Public T newInstance (): Only objects with non-private constructor and no parameters can be created; for example, new class ();
T classInstance. newIntance ();
This class is instantiated using a new expression with an empty parameter list. If the class has not been initialized, initialize the class.

(2 ).
1> first obtain a specified constructor,
2>. Call a method in the constructor,
T newInstance (Object... initargs ),
Initargs indicates the actual parameters required by the constructor.

Example 1:

Package cn.com. java. wwh. www;
Import java. io. Serializable;
Import java. lang. reflect. Constructor;
Import java. util. Date;
Import java. util. Map;


/**
* @ Category: Basic knowledge points for exercise reflection
*
*
* @ Author
* @ Version 1.0
* @ Creation Time: 9:14:13
*
*/


@ Deprecated
Class A extends Object implements Serializable {

Private A (String ch)
{
System. out. println (ch );

}

Public (){
}

Class B {

}
Class C {

}
}
Enum Gender {
MAN, WOMAN (), NONE {}
}
Public class Test {


/**
* @ Param args
* @ Throws Exception
*/
Public static void main (String [] args) throws Exception {
// TODO Auto-generated method stub


Class DateTest = new Date (). getClass ();
Class D1 = Date. class;
System. out. println (d1 = dateTest );
System. out. println (dateTest );
System. out. println ("Method 1 :");
System. out. println ("---->" + A. class. toString ());
// Permission name: package name + class name
String className = "cn.com. java. wwh. www. ";
Class Cla1 = Class. forName (className );
System. out. println (cla1 );
// Obtain the class by calling the object
Object testA = new ();
System. out. println ("using objects to get objects" + testA. getClass ());
// Public Annotation [] getAnnotations ()
// System. out. println (Class ) TestA). getAnnotations ());
// Handle enumeration types:
System. out. println ("Gender. MAN. getClass () ----->" + Gender. MAN. getClass ());
System. out. println ("Gender. WOMAN. getClass () ----->" + Gender. WOMAN. getClass ());
System. out. println ("Gender. NONE. getClass () ----->" + Gender. NONE. getClass ());
System. out. println ("Gender. MAN. getClass () ----->" + Gender. MAN. getDeclaringClass ());
System. out. println (Map. class );

// Nine pre-defined Class objects -----------------------------------
Int [] arry1 = {1, 2 };
Class Arr1 = arry1.getClass ();
Int [] arry2 = {1, 3, 5, 4 };
Class Arr2 = arry2.getClass ();
System. out. println (arry1 = arry2 );
System. out. print ("arr1 = arr2 -------> ");
System. out. println (arr1 = arr2); // true
Int [] [] arry3 = {};
Class Arr3 = arry3.getClass ();
System. out. print ("arr1 = arr3 -------> ");
System. out. println (arr1 = arr3); // false
// Another method for getting the Class Object of the array:
System. out. println (int [] []. class. toString (); // class [[I
/**
* Basic Java types (boolean, byte, char, short, int, long, float, and double)
* And the keyword void are also represented as Class objects.
They all correspond to this class attribute;
Their conversion classes all have TYPE constants. What they get is their basic TYPE bytecode;
Data Types (references and basics) all have class attributes;
*/
// Integer and int indicate different data types
System. out. println (int. class); // int
System. out. println (Integer. TYPE); // int
System. out. println (int. class = Integer. class); // flase
System. out. println (Integer. TYPE = int. class); // true
System. out. println (Integer. TYPE = Integer. TYPE); // true
System. out. println (Integer. TYPE = Integer. class); // false


// Method in Class = ----------------------->
Class TA = A. class;
System. out. println (tA );
/**
* Annotation [] getAnnotations () returns all comments on this element.
*/

System. out. println (tA. getAnnotations (). length );


/**
* Class [] GetClasses ()
Obtain all the public-modified internal classes of the Class described by the Class.

Class GetDeclaredClasses ()
Obtain all internal classes of the Class described by the Class, which are irrelevant to the access permission.
*/


Class [] InnerClass1 = tA. getClasses ();
System. out. println ("the length of innerClass is:" + innerClass1.length );
For (Class Inner: innerClass1)
{
System. out. println (inner. toString ());
}
Class [] InnerClass2 = tA. getDeclaredClasses ();
System. out. println ("output internal class irrelevant to access permission :");
System. out. println (innerClass2.length );
For (Class Inner: innerClass2)
{
System. out. println (inner. toString ());
}
/**
* Class [] GetInterfaces () determines the class or interface implemented by this object.
*/
Class [] GetInterfa = tA. getInterfaces ();
System. out. println ("All interfaces implemented by tA :");
For (Class Inter: getInterfa)
{
System. out. println (inter. toString ());
}
/** Public Constructor GetConstructor (Class ... ParameterTypes)
Throws NoSuchMethodException,
SecurityException
**/
Constructor [] Construc = tA. getConstructors ();
For (Constructor con: construc)
{
System. out. println (con. toString ());
}



}


}


Example 2:

Package cn.com. java. wwh. www;
Import java. lang. reflect. Constructor;
Import java. util. Date;
/**
* @ Class: creates an object Using Reflection
*
* @ Author
* @ Version 1.0
* @ Creation Time: 8:24:53
*
*/
Class Teacher {


Private Teacher (String name ){
System. out. println (name );
}
/* (Non-Javadoc)
* @ See java. lang. Object # toString ()
*/
@ Override
Public String toString (){
Return "Hello, teacher! ";
}

}
Public class NewInstanceDemo {
Public static void main (String [] args) throws Exception {
// Teacher teacher = new Teacher ();
// System. out. println (teacher );


Class Teacher1 = Teacher. class;
// Teacher = teacher1.newInstance ();
// System. out. println (teacher );
System. out. println ("--------------------------------> ");
// The second method of reflection:
Class Teacher3 = Teacher. class;
Constructor Teacher4 = teacher3.getDeclaredConstructor (String. class );
// Set the accessible
Teacher4.setAccessible (true );
// Construct an object
Teacher teacher5 = teacher4.newInstance ("one leaf fl ");
System. out. println (teacher5 );
CreateInstance ();


}
// Create a java. util. Date object
Public static void createInstance () throws Exception
{
// New Date ();
String className = "java. util. Date ";
Class DateClass = Class. forName (className );
Date date = (Date) dateClass. newInstance ();
System. out. println (date );
// Constructor, no Parameter
Constructor Date1 = (Constructor ) DateClass. getConstructor ();
System. out. println (date1.newInstance ());

// With Parameters
Constructor Date2 =
(Constructor ) DateClass. getConstructor (long. class );
System. out. println (date2.newInstance (10 ));

}

}

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.