11-java Study Notes-reflection

Source: Internet
Author: User

1. Reflection of the application scenario

I. Overview

Reflective technology:

Java reflection mechanism is in the running state, for any class, can know all the properties and methods of this class, for any one object, can call any of its methods and properties; This dynamically acquired information and the ability to dynamically invoke the method of an object is called the reflection mechanism of the Java language.

Second, the application scenario

An already available application because the program is ready to run and can no longer be added to the code. What should we do when we add a new feature to the program later? Just like our computer, later we may be mouse, keyboard, etc., so the computer gives us a USB interface, as long as the interface rules to meet the device, the computer can be loaded by the driver and other operations to use.

Then this program can be used, how to use the post-emergence function class?

A common practice is to provide a configuration file to extend the functionality of the class that later implements the program. Provide configuration files externally, so that later subclasses can directly configure the class name to the configuration file. The application reads the contents of the configuration file directly. and find the same class file as the given name. Do the following:

1) Load this class.

2) Create an object of the class.

3) Call the contents of the class.

When an application uses a class that is not deterministic, it is possible to have the user store the specific subclass in the configuration file by providing a configuration file. The program then uses the reflection technique to obtain the content of the specified class.

Benefit: The reflection technology greatly improves the expansibility of the program.


2. The cornerstone of reflection-class class contrast question: The person class represents people, its instance object is Zhang San, John Doe such a specific person, each Java class in a Java program belongs to the same class, and the Java class name that describes such things is class.
contrast question: What kind of a person does a lot of people say? What kind of class does a large number of Java classes represent?
Human person Java class. Class represents the Java class, and what are the individual instance objects corresponding to each other? Corresponding byte codes in memory for each class, 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, occupies a piece of storage space, the contents of this space is the class bytecode, different classes of bytecode is different, so they are in memory of the content is different, this space can be used by each object to represent, these objects are obviously the same type, What is this type? How to get the instance object (class type) corresponding to each byte code1. Class name, System.class Person.class 2. Object. GetClass () New Date (). GetClass () 3. Class.forName ("class name")//The class name can be a variable, dynamically get Class.forName ("Java.util.Date"); nine predefined class instance objects:       There are eight basic types (int, byte,long,float,double,short,char,boolean,) and void in Java
See the help of the class.isprimitive method Int.class = = Integer.type class instance object of array typeClass.isarray () in short, as long as the types that appear in the source program have their own class instance objects, for example, int[],void ...classReflecttest
{
PublicStaticvoidMain (string[] args)throwsException
{
String str1 = "abc";
Class cls1 = Str1.getclass ();
Class cls2 = String.class;
Class CLS3 = Class.forName ("java.lang.String");

System.out.println (CLS1==CLS2);//true
System.out.println (CLS2==CLS3);//true

//determines whether the specified Class object represents a base type.
System.out.println (Cls1.isprimitive ());//false

System.out.println (int.class= = Integer.class);//false
System.out.println (int.class= = Integer.type);//true

System.out.println (int[].class. isprimitive ());//false

//determines whether this class object represents an array class.
System.out.println (int[].class. IsArray ());//true

}
} 3. ReflectionReflection is the mapping of the various components in the Java class into the corresponding Java classes. For example, a Java class is represented by an object in a class class: member variables, methods, construction methods, packages, and so on, are represented by a Java class, like a car is a class, the engine in a car, a gearbox, etc. are also classes.      The class class that represents the Java class obviously has to provide a series of methods to obtain the variables, methods, constructs, modifiers, packages and other information, which are represented by the instance object of the corresponding class, which are field, method, Contructor, package, etc. 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 have been called by the method of the class class? How to use it? This is the point of learning and applying reflection. 4.Constructor classThe constructor class represents one of a class Construction Method
Import java.lang.reflect.*; Get a class all theConstruction method: Constructor [] constructors= class.forname ("java.lang.String"). GetConstructors (); get A certainConstruction method: Constructor Constructor = Class.forName ("java.lang.String"). GetConstructor (Stringbuffer.class); The type to use when obtaining the method creating an Instance object: Usual way: string str = new String (New StringBuffer ("abc"));     Reflection mode: String str = (string) constructor.newinstance (new StringBuffer ("abc")); Use the same type of instance object as above when calling the obtained method
class.newinstance () method: example: String obj = (string) class.forname ("java.lang.String"). newinstance ();     The method internally obtains the default construction method, and then creates the instance object with the constructor method. How is the specific code inside the method written? A caching mechanism is used to save the instance object of the default constructor method. 5.Field class
The field class represents one of a class member VariablesDemonstrates how to construct a Java class automatically with eclipse: does the resulting Field object correspond to the member variable above the class, or to the member variable on the object? The class has only one, and the instance object of the class has more than one, and if it is associated with an object, which object is associated? So the field FIELDX represents the definition of X, not the specific x variable. Example: 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); System.out.println (X.get (point));Importjava.lang.reflect.*;

classReflectpoint
{
PrivateintX
PublicintY

PublicReflectpoint (intXintY
{
Super();
This. x = x;
This. y = y;
}
}

classFielddemo
{
Public StaticvoidMain (string[] args)throwsException
{
Reflectpoint pt1 =NewReflectpoint (3,5);

//Field fieldx = Pt1.getclass (). GetField ("x");
Field fieldx = Pt1.getclass (). Getdeclaredfield ("X");
//violent reflexes
Fieldx.setaccessible (true);

Field Fieldy = Pt1.getclass (). GetField ("Y");
//What is the value of Fieldy?
System.out.println (Fieldx.get (PT1));
System.out.println (Fieldy.get (PT1));
}
Job: Change "B" in the string contents of any of the member variables of string types in any object to "a".Importjava.lang.reflect.*;

classReflectpoint
{
PrivateintX
Public intY
PublicString str1 = "Ball";
PublicString str2 = "basketball";
PublicString STR3 = "Apple";

PublicReflectpoint (intXintY
{
Super();
This. x = x;
This. y = y;
}
@Override
PublicString toString ()
{
returnSTR1 + ":" + str2 + ":" + str3;
}
}

classFieldtest
{
PublicStaticvoidMain (string[] args)throwsException
{
Reflectpoint pt1 =NewReflectpoint (3,5);

field[] fields = Pt1.getclass (). GetFields ();
for(Field field:fields)
{
//same byte code with = =
//if (Field.gettype (). Equals (String.class))
if(Field.gettype () = = String.class)
{
String oldValue = (string) field.get (PT1);
String newvalue = oldvalue.replace (' B ', ' a ');
Field.set (PT1, newvalue);
}
}

System.out.println (PT1);
}
} 6.Method classThe method class represents a member method in a class to get one of the methods in the class: example: Method charAt = Class.forName ("java.lang.String").      GetMethod ("CharAt", Int.class);     Parameter method name and parameter list call method: Usual way: System.out.println (Str.charat (1)); Reflection mode: System.out.println (charAt. Invoke(str, 1)); If passed to the method object InvokeThe first parameter of the () method is NULL, what does that mean? Indicates that the method object corresponds to a StaticMethod! (variadic) The difference between the Invoke method of jdk1.4 and jdk1.5: Jdk1.5:public object Invoke (Object Obj,object ... args) Jdk1.4:public object Invok E (Object obj,object[] args), that is, by jdk1.4 syntax, when an array needs to be passed as an argument to the Invoke method, each element in the array corresponds to one of the called methods parameter, the code that calls the CharAt method can also be rewritten as Jdk1.4 to Charat.invoke ("str", New Object[]{1}). 7. Performing the main method in a class in a reflective manner
Target: Write a program that can execute the main method in the class based on the class name provided by the user. After the normal way to adjust, we must understand why to use the reflective way to adjust ah? Problem: The parameter of the main method that launches the Java program is an array of strings, public static void main (string[] args), how do I pass arguments to the Invoke method when this main method is invoked by reflection? According to jdk1.5 syntax, the entire array is a parameter, and by jdk1.4 syntax, each element in the array corresponds to a parameter, and when a string array is passed as an argument to the Invoke method, what syntax does Javac follow? jdk1.5 must be compatible with the jdk1.4 syntax, which will be handled according to the jdk1.4 syntax, which is to break up the array into several separate parameters. Therefore, the code Mainmethod.invoke (null,new string[]{"xxx"}) cannot be used when passing arguments to the main method. Javac only interprets it as a jdk1.4 syntax and does not interpret it as a jdk1.5 syntax, so there is a problem with the wrong type of argument. Workaround: Mainmethod.invoke (null,new object[]{new string[]{"xxx"}}); Mainmethod.invoke (null, (Object) new string[]{"XXX"} ), the compiler will do special processing, compile without regard to the parameters as an array, it will not be broken into several parameters of the array 8. Reflection of Arrays
An array of the same dimension and element type belongs to the same type, that is, with the same class instance object. The Getsuperclass () method that represents the class instance object of an array returns the parent class that corresponds to the class of object. A one-dimensional array of basic types can be used as an object type, not as a object[] type, or as a one-dimensional array of non-primitive types, either as an object type or as a object[] type. The Arrays.aslist () method handles int[] and string[] differences. The array tool class is used to complete the reflection operation of an array. Study questions: How do I get the element type in the array? 9. The role of Reflection: implementing Framework FunctionsFramework and framework to solve the core issues I do the house sold to the user live, by the user to install Windows and doors and air conditioning, I do the house is the framework, users need to use my frame, the door and window into the framework I provide. The framework differs from the tool class, where the tool class is called by the user's class, while the framework invokes the user-supplied class. Core issues to be addressed by the framework when I write the Framework (house), you may still be in primary school, and you will not be able to write programs yet.     How can I write a framework program that calls into the class (Windows and doors) you write later? Because there is no way to know the name of the class to be called when the program is written, it is not possible to make an instance object of a class directly in the program, but to do so by reflection.     The synthesis case first creates an instance object of ArrayList and HashSet directly with the new statement, demonstrating the Equals and hashcode methods of automating the generation of reflectpoint classes with Eclipse, comparing the running result differences of two sets.     Then, instead of creating an instance object of ArrayList and HashSet in the form of a profile plus reflection, compare the observed run result differences. This paper introduces how to manage the resource files by Elipse.

11-java Study Notes-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.